SlideShare a Scribd company logo
4
PHP variables
4
similar to JavaScript, PHP variables are not declared, dynamically typed
scalar data types: Boolean, integer, double, string
compound data types: array, object
special types: resource, NULL
all variable names begin with $
<html>
<head>
<title>Server-side Fortune</title>
<?php
$list = array("Live long and prosper",
"Save for tomorrow",
"You will meet someone");
$fortune = $list[rand(0, count($list)-1)];
?>
</head>
<body>
<table border=1 align="center">
<tr><td>
<?php print($fortune); ?>
</table>
</body>
</html>
variables are flexible
 any unassigned variable has
value NULL
 can test if NULL using IsSet
e.g., IsSet($name)
 can set mode so that
unbound access is reported,
or automatically coerced to
default values
Most read
5
PHP: handling form data
5
 <html> <!-- helloNice.php -->
 <head> <title>Server-side Greeting</title> </head>
 <body>
 <?php
 $yourName = $_POST['yourName'];
 print("Hello and welcome to my page <i>$yourName</i>.<br />n");
 print("If you like it, " .
 "<a href='mailto:davereed@creighton.edu'>email me</a>!n");
 ?>
 </body>
 </html>
can write server-side programs in PHP as an alternative to CGI
 no need for CGIinput class, can use either GET or POST
 form data is automatically accessible via variable with form element name
 similar to Perl, '.' is used for string concatenation
<html> <!-- helloNicePHP.html -->
<head> <title>PHP Form Handling</title> </head>
<body>
<form action="http://empirical.cs.creighton.edu/~davereed/helloNice.php"
method="post">
Enter your name: <input type="text" name="yourName"/>
<br /><br />
<input type="submit" value="click for greeting" />
</form>
</body>
</html>
Most read
8
Word ladder in PHP
8
 <html>
 <head>
 <title>Word Ladder Challenge</title>
 <?php
 $dictionary = file("words5.txt");
 $start = $dictionary[rand(0, count($dictionary)-1)];
 $end = $dictionary[rand(0, count($dictionary)-1)];
 ?>
 </head>
 <body>
 <div style="text-align:center">
 <h2>Dave's Word Ladder Challenge</h2>
 <p>Create a word ladder between <b> <?php print($start); ?> </b>
 and <b> <?php print($end); ?> </b>
 <form name="ladderForm"
 action="http://empirical.cs.creighton.edu/~davereed/ladderCheck.php"
 method="post">
 <textarea name="ladder" rows=10 cols=8 wrap="virtual"></textarea>
 <br /><br />
 <input type="hidden" name="start" value="<?php print($start); ?>">
 <input type="hidden" name="end" value="<?php print($end); ?>">
 <input type="submit" value="Submit Ladder">
 </form>
 </div>
 </body>
 </html>
ladder.php contains start
of game:
• PHP displays start &
end words
• static HTML gives form
with text area & submit
button
Most read
Server-side programming & PHP
 server-side includes
 Netscape LiveWire
 Active Server Pages (ASP)
 Java Servlets
 PHP
− variables, control statements, file access
− form handling
− file uploading, email redirection
Internet & Web Programming
PHP
2
 PHP is similar to JavaScript, only server-side
PHP code is embedded in HTML using tags
when a page request arrives, the server recognizes PHP content via the file
extension (.php , .php3, or .phtml)
the server executes the PHP code, substitutes output into the HTML
the resulting page is then downloaded to the client
user never sees the PHP code, only the output in the page
developed in 1995 by Rasmus Lerdorf (member of the Apache Group)
 originally designed as a tool for tracking visitors at Lerdorf's Web site
 within 2 years, widely used in conjunction with the Apache server
 developed into full-featured, scripting language for server-side programming
 free, open-source
 server plug-ins exist for various servers
PHP execution
3
PHP code can be embedded within a <?php...?> tag
output is displayed using print
<!-- hello.php -->
<html>
<head>
<title>Server-side Hello</title>
</head>
<body>
<table border=1 align="center">
<tr><td>
<?php print("Hello and welcome to <i>my</i> page!"); ?>
</table>
</body>
</html>
<!-- hello.php -->
<html>
<head>
<title>Server-side Hello</title>
</head>
<body>
<table border=1 align="center">
<tr><td>
Hello and welcome to <i>my</i> page!
</table>
</body>
</html>
the server executes the
print statement, substitutes
output, downloads
resulting page
PHP variables
4
similar to JavaScript, PHP variables are not declared, dynamically typed
scalar data types: Boolean, integer, double, string
compound data types: array, object
special types: resource, NULL
all variable names begin with $
<html>
<head>
<title>Server-side Fortune</title>
<?php
$list = array("Live long and prosper",
"Save for tomorrow",
"You will meet someone");
$fortune = $list[rand(0, count($list)-1)];
?>
</head>
<body>
<table border=1 align="center">
<tr><td>
<?php print($fortune); ?>
</table>
</body>
</html>
variables are flexible
 any unassigned variable has
value NULL
 can test if NULL using IsSet
e.g., IsSet($name)
 can set mode so that
unbound access is reported,
or automatically coerced to
default values
PHP: handling form data
5
 <html> <!-- helloNice.php -->
 <head> <title>Server-side Greeting</title> </head>
 <body>
 <?php
 $yourName = $_POST['yourName'];
 print("Hello and welcome to my page <i>$yourName</i>.<br />n");
 print("If you like it, " .
 "<a href='mailto:davereed@creighton.edu'>email me</a>!n");
 ?>
 </body>
 </html>
can write server-side programs in PHP as an alternative to CGI
 no need for CGIinput class, can use either GET or POST
 form data is automatically accessible via variable with form element name
 similar to Perl, '.' is used for string concatenation
<html> <!-- helloNicePHP.html -->
<head> <title>PHP Form Handling</title> </head>
<body>
<form action="http://empirical.cs.creighton.edu/~davereed/helloNice.php"
method="post">
Enter your name: <input type="text" name="yourName"/>
<br /><br />
<input type="submit" value="click for greeting" />
</form>
</body>
</html>
PHP: email database example
6
<html>
<head> <title>PHP Email DB</title>
<?php
$emailDB = array("Jim Carlson", "carlsn@creighton.edu",
"Davendar Malik", "malik@creighton.edu",
"Prem Nair", "psnair@creighton.edu",
"Dave Reed", "davereed@creighton.edu",
"Mark Wierman", "wierman@creighton.edu");
?>
</head>
<body>
<?php
$person = $_POST['person'];
print("Search results for: " . $person . "<br /><br />n");
$found = false;
for ($i = 0; $i < count($emailDB); $i+=2) {
if ($person == "" ||
strpos("?".strtolower($emailDB[$i]), strtolower($person))) {
$entry1 = $emailDB[$i];
$entry2 = $emailDB[$i+1];
print("$entry1: <a href='mailto:$entry2'>$entry2</a><br />n");
$found = true;
}
}
if (!$found) {
print("No matching names were found. Please try again.<br />n");
}
?>
</body>
</html>
since PHP source is not
seen by user, can
embed protected data
safely
string functions
include:
• strlen
• strcmp
• strpos
• substr
• strtolower
• strtoupper
• trim
PHP: file example
7
<html>
<head>
<title>PHP Email DB</title>
<?php
$emailDB = file("email.txt");
?>
</head>
<body>
<?php
$person = $_POST['person'];
print("Search results for: " . $person . "<br /><br />n");
$found = false;
for ($i = 0; $i < count($emailDB); $i+=2) {
if ($person == "" ||
strpos("?".strtolower($emailDB[$i]), strtolower($person))) {
$entry1 = $emailDB[$i];
$entry2 = $emailDB[$i+1];
print("$entry1: <a href='mailto:$entry2'>$entry2</a><br />n");
$found = true;
}
}
if (!$found) {
print("No matching names were found. Please try again.<br />n");
}
?>
</body>
</html>
various routines exist
for reading/writing files
simplest is file, which
reads a file into an array
of strings (one per line)
Word ladder in PHP
8
 <html>
 <head>
 <title>Word Ladder Challenge</title>
 <?php
 $dictionary = file("words5.txt");
 $start = $dictionary[rand(0, count($dictionary)-1)];
 $end = $dictionary[rand(0, count($dictionary)-1)];
 ?>
 </head>
 <body>
 <div style="text-align:center">
 <h2>Dave's Word Ladder Challenge</h2>
 <p>Create a word ladder between <b> <?php print($start); ?> </b>
 and <b> <?php print($end); ?> </b>
 <form name="ladderForm"
 action="http://empirical.cs.creighton.edu/~davereed/ladderCheck.php"
 method="post">
 <textarea name="ladder" rows=10 cols=8 wrap="virtual"></textarea>
 <br /><br />
 <input type="hidden" name="start" value="<?php print($start); ?>">
 <input type="hidden" name="end" value="<?php print($end); ?>">
 <input type="submit" value="Submit Ladder">
 </form>
 </div>
 </body>
 </html>
ladder.php contains start
of game:
• PHP displays start &
end words
• static HTML gives form
with text area & submit
button
Word ladder in PHP
9
 <html>
 <head>
 <title>Word Ladder Challenge</title>
 <?php
 function binsearch($needle, $haystack)
 {
 $high = count($haystack)-1;
 $low = 0;
 while ($low <= $high){
 $middle = floor(($high + $low) / 2);
 if (trim($haystack[$middle]) == trim($needle)){
 return true;
 }
 else if (trim($haystack[$middle]) < trim($needle)){
 $low = $middle+1;
 }
 else{
 $high = $middle-1;
 }
 }
 return false;
 }
 function LetterDiff($word1, $word2)
 {
 $diffCount = 0;
 for ($z = 0; $z < strlen(word1); $z++) {
 if ($word1{$z} != $word2{$z}) {
 $diffCount++;
 }
 }
 return $diffCount;
 }
 ?>
 </head>
ladderCheck.php page
• defines functions for
checking a ladder
• static HTML gives form
with text area & submit
button
10
 <body>
 <div style="text-align:center">
 <h2>Dave's Word Ladder Challenge</h2>
 <?php
 $dictionary = file("words5.txt");
 $start = trim($_POST['start']);
 $end = trim($_POST['end']);
 $ladder = trim($_POST['ladder']);
 $ladderArr = preg_split("/[ns]+/", $ladder);
 if ($start != $ladderArr[0]) {
 print("INVALID LADDER: starting word should be $start<br />");
 }
 else if ($end != $ladderArr[count($ladderArr)-1]) {
 print("INVALID LADDER: ending word should be $end<br />");
 }
 else {
 $OK = true;
 for ($i = 1; $i < count($ladderArr) and $OK; $i++) {
 if (!binsearch($ladderArr[$i], $dictionary)) {
 print("INVALID LADDER: ".$ladderArr[$i]." is not a legal word.<br />");
 $OK = false;
 }
 else if (LetterDiff($ladderArr[$i], $ladderArr[$i-1]) != 1) {
 print("INVALID LADDER: ".$ladderArr[$i]." is not connected to" .
 $ladderArr[$i-1].".<br />");
 $OK = false;
 }
 }
 if ($OK) {
 print("$ladder is a valid ladder. Congratulations!<br />");
 }
 }
 ?>
 <form name="ladderForm"
 action="http://empirical.cs.creighton.edu/~davereed/ladder.php" method="post">
 <input type="submit" value="Play Again?">
 </form>
 </div></body></html>
rest of ladderCheck.php
• gets data from form
elements
• verifies the correctness
of the ladder
Standalone PHP
11
 <?php
 $emailDB = file("email.txt");
 $person = $_POST['person'];
 print("Search results for: " . $person . "<br /><br />n");
 $found = false;
 for ($i = 0; $i < count($emailDB); $i+=2) {
 if ($person == "" ||
 strpos("?".strtolower($emailDB[$i]), strtolower($person))) {
 $entry1 = $emailDB[$i];
 $entry2 = $emailDB[$i+1];
 print("$entry1: <a href='mailto:$entry2'>" .
 "$entry2</a><br />n");
 $found = true;
 }
 }
 if (!$found) {
 print("No matching names were found. Please try again.<br />n");
 }
 ?>
previous examples have shown how PHP code can be nested in HTML
 browsers don't really require HTML, HEAD, BODY tags
 if no static content in the page, can ignore HTML elements
 PHP output text will be treated as the body of a default Web page
Another example: file uploading
12
the HTML file input element allows the user to browse for a file
<input type="file" name="ELEMENT_NAME">
 once the user selects a file, can use a submit button to call a CGI or PHP
program to process that file
<html>
<head>
<title>Simple File Uploader</title>
</head>
<body>
<form name="uploader" action="http://empirical.cs.creighton.edu/~davereed/upload.php"
enctype="multipart/form-data" method="post">
Select file for uploading: <input type="file" name="userfile">
<br /><br />
<input type="submit" value="Upload File">
</form>
</body>
</html>
PHP file manipulations
13
 <?php
 $BASEDIR = "/var/www/davereed/files/";
 if (!file_exists($BASEDIR.$_FILES['userfile']['name'])) {
 move_uploaded_file($_FILES['userfile']['tmp_name'],
 $BASEDIR.$_FILES['userfile']['name']);
 print("File uploaded successfully");
 }
 else {
 print("File already exists - no upload performed.");
 }
 ?>
PHP provides extensive support for file/directory manipulation
$_FILES[$FORM_ELE_NAME]['name'] original name of the file uploaded via
the specified form input element
$_FILES[$FORM_ELE_NAME]['tmp_name'] temporary name of the file where it
is uploaded onto the server
move_uploaded_file($_FILES[$FORM_ELE_NAME]['tmp_name'], $FILE_PATH_NAME)
copies uploaded file to specified loc.
Robust file uploading
<html>
<head>
<title>Simple File Uploader</title>
</head>
<body>
<form name="uploader" action="http://empirical.cs.creighton.edu/~davereed/upload.php"
enctype="multipart/form-data" method="post">
<table>
<tr><td>Enter your user name:
<td><input type="text" name="userID" size=10 value="">
<tr><td>Select file for uploading:
<td><input type="file" name="userfile">
</table>
<input type="submit" value="Upload File">
</form>
</body>
</html>
14
could utilize other PHP features to make file uploading more robust
 allow multiple students to submit same assignment
 each student specifies a user name, file is uploaded into a subdirectory
Robust file uploading
15
 <?php
 $userID = $_POST['userID'];
 $BASEDIR = "/var/www/davereed/files/";
 $_FILES['userfile']['name'] = explode(' ', $_FILES['userfile']['name']);
 $_FILES['userfile']['name'] = implode('_', $_FILES['userfile']['name']);
 if (IsSet($userID)) {
 $BASEDIR = $BASEDIR.$userID."/";
 if (!file_exists($BASEDIR)) {
 mkdir($BASEDIR, 755);
 }
 }
 if (!file_exists($BASEDIR.$_FILES['userfile']['name'])) {
 move_uploaded_file($_FILES['userfile']['tmp_name'],
 $BASEDIR.$_FILES['userfile']['name']);
 print("File uploaded successfully");
 }
 else {
 print("File already exists - no upload performed.");
 }
 ?>
get the user ID from text box
replace ' ' with '_'
in file name
if user ID is entered,
extend path & create
directory if deosn't
already exist
Homework submission program
16
 Joel van Brandwijk has extended this program to create a generic homework
submission utility
 student interface is password driven
 connects with Active Directory to verify password for given user name
 student can select among current classes and assignments
 course/assignment info is stored in an SQL database, accessed via PHP
 student can specify multiple files, even structure into subdirectories for uploading
 instructor interface is also password driven
 checks database to make sure a legit instructor, then checks password
 instructor can add/remove class, add/remove students, add/remove assignments
 info is stored in SQL database, accessed via PHP
 instructor can download submissions to local computer for grading
empirical.cs.creighton.edu/submissions
Example: email redirection
17
most Web sites give visitor option of sending feedback
 can be accomplished using mailto: link
<a href=mailto:davereed@creighton.edu>Feedback?</a>
potential problem: not all client computers are email-enabled
 can instead use a PHP program as a front-end for email
 user enters address, subject, message
 PHP program receives & bundles these pieces into an email message, sends on
 if desired, can be used for anonymous email redirection (no return address supplied)
Example: email redirection
<?php function show_form($email="",$message="",$subject="") { ?>
<h2>Send Me an E-mail</h2>
<form action="http://empirical.cs.creighton.edu/~davereed/email.php"
 method="post">
Your E-mail address:<br>
<input type=text name=email size=30 value="<?php print($email); ?>"><br>
The Subject:<br>
<input type=text name=subject size=30 value="<?php print($subject); ?>"><br>
Your Message:<br>
<textarea rows=10 cols=50 name=message><?php print($message); ?></textarea><br>
<input type=submit value="Send E-mail">
</form>
<?php }
.
.
.
18
this part of the page
defines a function for
generating the input
page
Example: email redirection
(cont.)
19
 $email = $_POST['email'];
 $subject = $_POST['subject'];
 $message = $_POST['message'];
 if (!isset($email) or !isset($message)) {
 show_form();
 }
 else {
 if (empty($message)) {
 print("Please write something and resend.");
 show_form($email,$message,$subject);
 }
 else {
 if (empty($email)) {
 $email="anonymous";
 }
 if (empty($subject)) {
 $subject="stuff";
 }
 $sent = mail( "davereed@creighton.edu", $subject, $message, "From: $email" );
 if ($sent) {
 print("<H1>Your Message Has Been Sent.</H1>");
 }
 else {
 print("<p>The server was unable to send your mail.");
 }
 }
 }
 ?>
if no inputs to page (not called from
form), show input page
if message field is empty, warn user
and show the input page again
if email or subject fields are empty,
give default values
send the email message and
report status

More Related Content

What's hot (20)

Introduction to PHP
Introduction to PHPIntroduction to PHP
Introduction to PHP
Jussi Pohjolainen
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
Compare Infobase Limited
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
Shlomi Komemi
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Php Using Arrays
Php Using ArraysPhp Using Arrays
Php Using Arrays
mussawir20
 
Php forms
Php formsPhp forms
Php forms
Anne Lee
 
Php
PhpPhp
Php
Shyam Khant
 
PHP
PHPPHP
PHP
Steve Fort
 
Node.js Express
Node.js  ExpressNode.js  Express
Node.js Express
Eyal Vardi
 
Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1Web Development Course: PHP lecture 1
Web Development Course: PHP lecture 1
Gheyath M. Othman
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
Nidhi mishra
 
PHP - Introduction to PHP Fundamentals
PHP -  Introduction to PHP FundamentalsPHP -  Introduction to PHP Fundamentals
PHP - Introduction to PHP Fundamentals
Vibrant Technologies & Computers
 
Php technical presentation
Php technical presentationPhp technical presentation
Php technical presentation
dharmendra kumar dhakar
 
Introduction To PHP
Introduction To PHPIntroduction To PHP
Introduction To PHP
Shweta A
 
Php and MySQL
Php and MySQLPhp and MySQL
Php and MySQL
Tiji Thomas
 
JavaScript Basic
JavaScript BasicJavaScript Basic
JavaScript Basic
Finsa Nurpandi
 
Express js
Express jsExpress js
Express js
Manav Prasad
 
Regular Expressions in PHP
Regular Expressions in PHPRegular Expressions in PHP
Regular Expressions in PHP
Andrew Kandels
 
PHP Workshop Notes
PHP Workshop NotesPHP Workshop Notes
PHP Workshop Notes
Pamela Fox
 

Similar to PHP POWERPOINT SLIDES (20)

Php mysql
Php mysqlPhp mysql
Php mysql
Ajit Yadav
 
Php introduction
Php introductionPhp introduction
Php introduction
Osama Ghandour Geris
 
Phpbasics
PhpbasicsPhpbasics
Phpbasics
PrinceGuru MS
 
Wt unit 4 server side technology-2
Wt unit 4 server side technology-2Wt unit 4 server side technology-2
Wt unit 4 server side technology-2
PUNE VIDYARTHI GRIHA'S COLLEGE OF ENGINEERING, NASHIK
 
PHP
PHPPHP
PHP
sometech
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
MercyL2
 
introduction_php.ppt
introduction_php.pptintroduction_php.ppt
introduction_php.ppt
ArunKumar313658
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
GiyaShefin
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHPQuick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 
Day1
Day1Day1
Day1
IRWAA LLC
 
Basics PHP
Basics PHPBasics PHP
Basics PHP
Alokin Software Pvt Ltd
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
Intro to PHP for Students and professionals
Intro to PHP for Students and professionalsIntro to PHP for Students and professionals
Intro to PHP for Students and professionals
cuyak
 
Php Lecture Notes
Php Lecture NotesPhp Lecture Notes
Php Lecture Notes
Santhiya Grace
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
Annujj Agrawaal
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
SHARANBAJWA
 
WT_PHP_PART1.pdf
WT_PHP_PART1.pdfWT_PHP_PART1.pdf
WT_PHP_PART1.pdf
HambardeAtharva
 
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
Unit 5-PHP  Declaring variables, data types, array, string, operators, Expres...Unit 5-PHP  Declaring variables, data types, array, string, operators, Expres...
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
DRambabu3
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
MercyL2
 
10_introduction_php.ppt
10_introduction_php.ppt10_introduction_php.ppt
10_introduction_php.ppt
GiyaShefin
 
Quick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHPQuick beginner to Lower-Advanced guide/tutorial in PHP
Quick beginner to Lower-Advanced guide/tutorial in PHP
Sanju Sony Kurian
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 
Winter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHPWinter%200405%20-%20Beginning%20PHP
Winter%200405%20-%20Beginning%20PHP
tutorialsruby
 
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
Php mysql classes in navi-mumbai,php-mysql course provider-in-navi-mumbai,bes...
anshkhurana01
 
Intro to PHP for Students and professionals
Intro to PHP for Students and professionalsIntro to PHP for Students and professionals
Intro to PHP for Students and professionals
cuyak
 
PHP language presentation
PHP language presentationPHP language presentation
PHP language presentation
Annujj Agrawaal
 
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
Unit 5-PHP  Declaring variables, data types, array, string, operators, Expres...Unit 5-PHP  Declaring variables, data types, array, string, operators, Expres...
Unit 5-PHP Declaring variables, data types, array, string, operators, Expres...
DRambabu3
 
Ad

More from Ismail Mukiibi (15)

Relational database (Unit 2)
Relational database (Unit 2)Relational database (Unit 2)
Relational database (Unit 2)
Ismail Mukiibi
 
Relational data base management system (Unit 1)
Relational data base management system (Unit 1)Relational data base management system (Unit 1)
Relational data base management system (Unit 1)
Ismail Mukiibi
 
Quality of service
Quality of serviceQuality of service
Quality of service
Ismail Mukiibi
 
IP/MAC Address Translation
IP/MAC Address TranslationIP/MAC Address Translation
IP/MAC Address Translation
Ismail Mukiibi
 
Traffic Characterization
Traffic CharacterizationTraffic Characterization
Traffic Characterization
Ismail Mukiibi
 
Html notes
Html notesHtml notes
Html notes
Ismail Mukiibi
 
Microprocessor application (Introduction)
Microprocessor application (Introduction)Microprocessor application (Introduction)
Microprocessor application (Introduction)
Ismail Mukiibi
 
Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2
Ismail Mukiibi
 
Advanced computer architect lesson 3 and 4
Advanced computer architect lesson 3 and 4Advanced computer architect lesson 3 and 4
Advanced computer architect lesson 3 and 4
Ismail Mukiibi
 
Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6
Ismail Mukiibi
 
Pc hardware course work
Pc hardware course workPc hardware course work
Pc hardware course work
Ismail Mukiibi
 
Mac addresses(media access control)
Mac addresses(media access control)Mac addresses(media access control)
Mac addresses(media access control)
Ismail Mukiibi
 
Kinds of networks
Kinds of networksKinds of networks
Kinds of networks
Ismail Mukiibi
 
Why building collapse in kampala
Why building collapse in kampalaWhy building collapse in kampala
Why building collapse in kampala
Ismail Mukiibi
 
Compare peer
Compare peerCompare peer
Compare peer
Ismail Mukiibi
 
Relational database (Unit 2)
Relational database (Unit 2)Relational database (Unit 2)
Relational database (Unit 2)
Ismail Mukiibi
 
Relational data base management system (Unit 1)
Relational data base management system (Unit 1)Relational data base management system (Unit 1)
Relational data base management system (Unit 1)
Ismail Mukiibi
 
IP/MAC Address Translation
IP/MAC Address TranslationIP/MAC Address Translation
IP/MAC Address Translation
Ismail Mukiibi
 
Traffic Characterization
Traffic CharacterizationTraffic Characterization
Traffic Characterization
Ismail Mukiibi
 
Microprocessor application (Introduction)
Microprocessor application (Introduction)Microprocessor application (Introduction)
Microprocessor application (Introduction)
Ismail Mukiibi
 
Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2Advanced computer architecture lesson 1 and 2
Advanced computer architecture lesson 1 and 2
Ismail Mukiibi
 
Advanced computer architect lesson 3 and 4
Advanced computer architect lesson 3 and 4Advanced computer architect lesson 3 and 4
Advanced computer architect lesson 3 and 4
Ismail Mukiibi
 
Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6Advanced computer architecture lesson 5 and 6
Advanced computer architecture lesson 5 and 6
Ismail Mukiibi
 
Pc hardware course work
Pc hardware course workPc hardware course work
Pc hardware course work
Ismail Mukiibi
 
Mac addresses(media access control)
Mac addresses(media access control)Mac addresses(media access control)
Mac addresses(media access control)
Ismail Mukiibi
 
Why building collapse in kampala
Why building collapse in kampalaWhy building collapse in kampala
Why building collapse in kampala
Ismail Mukiibi
 
Ad

Recently uploaded (20)

Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Safe Software
 
Scalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple DevicesScalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple Devices
Scalefusion
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 
Bonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdfBonk coin airdrop_ Everything You Need to Know.pdf
Bonk coin airdrop_ Everything You Need to Know.pdf
Herond Labs
 
IBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - IntroductionIBM Rational Unified Process For Software Engineering - Introduction
IBM Rational Unified Process For Software Engineering - Introduction
Gaurav Sharma
 
Automating Map Production With FME and Python
Automating Map Production With FME and PythonAutomating Map Production With FME and Python
Automating Map Production With FME and Python
Safe Software
 
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink TemplateeeeeeeeeeeeeeeeeeeeeeeeeeNeuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
Neuralink Templateeeeeeeeeeeeeeeeeeeeeeeeee
alexandernoetzold
 
Leveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer IntentsLeveraging Foundation Models to Infer Intents
Leveraging Foundation Models to Infer Intents
Keheliya Gallaba
 
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptxIMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
IMAGE CLASSIFICATION USING CONVOLUTIONAL NEURAL NETWORK.P.pptx
usmanch7829
 
Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4Software Engineering Process, Notation & Tools Introduction - Part 4
Software Engineering Process, Notation & Tools Introduction - Part 4
Gaurav Sharma
 
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Scaling FME Flow on Demand with Kubernetes: A Case Study At Cadac Group SaaS ...
Safe Software
 
Scalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple DevicesScalefusion Remote Access for Apple Devices
Scalefusion Remote Access for Apple Devices
Scalefusion
 
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The SequelMarketo & Dynamics can be Most Excellent to Each Other – The Sequel
Marketo & Dynamics can be Most Excellent to Each Other – The Sequel
BradBedford3
 
Boost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for SchoolsBoost Student Engagement with Smart Attendance Software for Schools
Boost Student Engagement with Smart Attendance Software for Schools
Visitu
 
Best Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small BusinessesBest Inbound Call Tracking Software for Small Businesses
Best Inbound Call Tracking Software for Small Businesses
TheTelephony
 
14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework14 Years of Developing nCine - An Open Source 2D Game Framework
14 Years of Developing nCine - An Open Source 2D Game Framework
Angelo Theodorou
 
Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...Online Queue Management System for Public Service Offices [Focused on Municip...
Online Queue Management System for Public Service Offices [Focused on Municip...
Rishab Acharya
 
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptxHow AI Can Improve Media Quality Testing Across Platforms (1).pptx
How AI Can Improve Media Quality Testing Across Platforms (1).pptx
kalichargn70th171
 
Key AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence CompaniesKey AI Technologies Used by Indian Artificial Intelligence Companies
Key AI Technologies Used by Indian Artificial Intelligence Companies
Mypcot Infotech
 
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-OffMicro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Micro-Metrics Every Performance Engineer Should Validate Before Sign-Off
Tier1 app
 
Agile Software Engineering Methodologies
Agile Software Engineering MethodologiesAgile Software Engineering Methodologies
Agile Software Engineering Methodologies
Gaurav Sharma
 
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdfTop 11 Fleet Management Software Providers in 2025 (2).pdf
Top 11 Fleet Management Software Providers in 2025 (2).pdf
Trackobit
 
The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...The rise of e-commerce has redefined how retailers operate—and reconciliation...
The rise of e-commerce has redefined how retailers operate—and reconciliation...
Prachi Desai
 

PHP POWERPOINT SLIDES

  • 1. Server-side programming & PHP  server-side includes  Netscape LiveWire  Active Server Pages (ASP)  Java Servlets  PHP − variables, control statements, file access − form handling − file uploading, email redirection Internet & Web Programming
  • 2. PHP 2  PHP is similar to JavaScript, only server-side PHP code is embedded in HTML using tags when a page request arrives, the server recognizes PHP content via the file extension (.php , .php3, or .phtml) the server executes the PHP code, substitutes output into the HTML the resulting page is then downloaded to the client user never sees the PHP code, only the output in the page developed in 1995 by Rasmus Lerdorf (member of the Apache Group)  originally designed as a tool for tracking visitors at Lerdorf's Web site  within 2 years, widely used in conjunction with the Apache server  developed into full-featured, scripting language for server-side programming  free, open-source  server plug-ins exist for various servers
  • 3. PHP execution 3 PHP code can be embedded within a <?php...?> tag output is displayed using print <!-- hello.php --> <html> <head> <title>Server-side Hello</title> </head> <body> <table border=1 align="center"> <tr><td> <?php print("Hello and welcome to <i>my</i> page!"); ?> </table> </body> </html> <!-- hello.php --> <html> <head> <title>Server-side Hello</title> </head> <body> <table border=1 align="center"> <tr><td> Hello and welcome to <i>my</i> page! </table> </body> </html> the server executes the print statement, substitutes output, downloads resulting page
  • 4. PHP variables 4 similar to JavaScript, PHP variables are not declared, dynamically typed scalar data types: Boolean, integer, double, string compound data types: array, object special types: resource, NULL all variable names begin with $ <html> <head> <title>Server-side Fortune</title> <?php $list = array("Live long and prosper", "Save for tomorrow", "You will meet someone"); $fortune = $list[rand(0, count($list)-1)]; ?> </head> <body> <table border=1 align="center"> <tr><td> <?php print($fortune); ?> </table> </body> </html> variables are flexible  any unassigned variable has value NULL  can test if NULL using IsSet e.g., IsSet($name)  can set mode so that unbound access is reported, or automatically coerced to default values
  • 5. PHP: handling form data 5  <html> <!-- helloNice.php -->  <head> <title>Server-side Greeting</title> </head>  <body>  <?php  $yourName = $_POST['yourName'];  print("Hello and welcome to my page <i>$yourName</i>.<br />n");  print("If you like it, " .  "<a href='mailto:[email protected]'>email me</a>!n");  ?>  </body>  </html> can write server-side programs in PHP as an alternative to CGI  no need for CGIinput class, can use either GET or POST  form data is automatically accessible via variable with form element name  similar to Perl, '.' is used for string concatenation <html> <!-- helloNicePHP.html --> <head> <title>PHP Form Handling</title> </head> <body> <form action="http://empirical.cs.creighton.edu/~davereed/helloNice.php" method="post"> Enter your name: <input type="text" name="yourName"/> <br /><br /> <input type="submit" value="click for greeting" /> </form> </body> </html>
  • 6. PHP: email database example 6 <html> <head> <title>PHP Email DB</title> <?php $emailDB = array("Jim Carlson", "[email protected]", "Davendar Malik", "[email protected]", "Prem Nair", "[email protected]", "Dave Reed", "[email protected]", "Mark Wierman", "[email protected]"); ?> </head> <body> <?php $person = $_POST['person']; print("Search results for: " . $person . "<br /><br />n"); $found = false; for ($i = 0; $i < count($emailDB); $i+=2) { if ($person == "" || strpos("?".strtolower($emailDB[$i]), strtolower($person))) { $entry1 = $emailDB[$i]; $entry2 = $emailDB[$i+1]; print("$entry1: <a href='mailto:$entry2'>$entry2</a><br />n"); $found = true; } } if (!$found) { print("No matching names were found. Please try again.<br />n"); } ?> </body> </html> since PHP source is not seen by user, can embed protected data safely string functions include: • strlen • strcmp • strpos • substr • strtolower • strtoupper • trim
  • 7. PHP: file example 7 <html> <head> <title>PHP Email DB</title> <?php $emailDB = file("email.txt"); ?> </head> <body> <?php $person = $_POST['person']; print("Search results for: " . $person . "<br /><br />n"); $found = false; for ($i = 0; $i < count($emailDB); $i+=2) { if ($person == "" || strpos("?".strtolower($emailDB[$i]), strtolower($person))) { $entry1 = $emailDB[$i]; $entry2 = $emailDB[$i+1]; print("$entry1: <a href='mailto:$entry2'>$entry2</a><br />n"); $found = true; } } if (!$found) { print("No matching names were found. Please try again.<br />n"); } ?> </body> </html> various routines exist for reading/writing files simplest is file, which reads a file into an array of strings (one per line)
  • 8. Word ladder in PHP 8  <html>  <head>  <title>Word Ladder Challenge</title>  <?php  $dictionary = file("words5.txt");  $start = $dictionary[rand(0, count($dictionary)-1)];  $end = $dictionary[rand(0, count($dictionary)-1)];  ?>  </head>  <body>  <div style="text-align:center">  <h2>Dave's Word Ladder Challenge</h2>  <p>Create a word ladder between <b> <?php print($start); ?> </b>  and <b> <?php print($end); ?> </b>  <form name="ladderForm"  action="http://empirical.cs.creighton.edu/~davereed/ladderCheck.php"  method="post">  <textarea name="ladder" rows=10 cols=8 wrap="virtual"></textarea>  <br /><br />  <input type="hidden" name="start" value="<?php print($start); ?>">  <input type="hidden" name="end" value="<?php print($end); ?>">  <input type="submit" value="Submit Ladder">  </form>  </div>  </body>  </html> ladder.php contains start of game: • PHP displays start & end words • static HTML gives form with text area & submit button
  • 9. Word ladder in PHP 9  <html>  <head>  <title>Word Ladder Challenge</title>  <?php  function binsearch($needle, $haystack)  {  $high = count($haystack)-1;  $low = 0;  while ($low <= $high){  $middle = floor(($high + $low) / 2);  if (trim($haystack[$middle]) == trim($needle)){  return true;  }  else if (trim($haystack[$middle]) < trim($needle)){  $low = $middle+1;  }  else{  $high = $middle-1;  }  }  return false;  }  function LetterDiff($word1, $word2)  {  $diffCount = 0;  for ($z = 0; $z < strlen(word1); $z++) {  if ($word1{$z} != $word2{$z}) {  $diffCount++;  }  }  return $diffCount;  }  ?>  </head> ladderCheck.php page • defines functions for checking a ladder • static HTML gives form with text area & submit button
  • 10. 10  <body>  <div style="text-align:center">  <h2>Dave's Word Ladder Challenge</h2>  <?php  $dictionary = file("words5.txt");  $start = trim($_POST['start']);  $end = trim($_POST['end']);  $ladder = trim($_POST['ladder']);  $ladderArr = preg_split("/[ns]+/", $ladder);  if ($start != $ladderArr[0]) {  print("INVALID LADDER: starting word should be $start<br />");  }  else if ($end != $ladderArr[count($ladderArr)-1]) {  print("INVALID LADDER: ending word should be $end<br />");  }  else {  $OK = true;  for ($i = 1; $i < count($ladderArr) and $OK; $i++) {  if (!binsearch($ladderArr[$i], $dictionary)) {  print("INVALID LADDER: ".$ladderArr[$i]." is not a legal word.<br />");  $OK = false;  }  else if (LetterDiff($ladderArr[$i], $ladderArr[$i-1]) != 1) {  print("INVALID LADDER: ".$ladderArr[$i]." is not connected to" .  $ladderArr[$i-1].".<br />");  $OK = false;  }  }  if ($OK) {  print("$ladder is a valid ladder. Congratulations!<br />");  }  }  ?>  <form name="ladderForm"  action="http://empirical.cs.creighton.edu/~davereed/ladder.php" method="post">  <input type="submit" value="Play Again?">  </form>  </div></body></html> rest of ladderCheck.php • gets data from form elements • verifies the correctness of the ladder
  • 11. Standalone PHP 11  <?php  $emailDB = file("email.txt");  $person = $_POST['person'];  print("Search results for: " . $person . "<br /><br />n");  $found = false;  for ($i = 0; $i < count($emailDB); $i+=2) {  if ($person == "" ||  strpos("?".strtolower($emailDB[$i]), strtolower($person))) {  $entry1 = $emailDB[$i];  $entry2 = $emailDB[$i+1];  print("$entry1: <a href='mailto:$entry2'>" .  "$entry2</a><br />n");  $found = true;  }  }  if (!$found) {  print("No matching names were found. Please try again.<br />n");  }  ?> previous examples have shown how PHP code can be nested in HTML  browsers don't really require HTML, HEAD, BODY tags  if no static content in the page, can ignore HTML elements  PHP output text will be treated as the body of a default Web page
  • 12. Another example: file uploading 12 the HTML file input element allows the user to browse for a file <input type="file" name="ELEMENT_NAME">  once the user selects a file, can use a submit button to call a CGI or PHP program to process that file <html> <head> <title>Simple File Uploader</title> </head> <body> <form name="uploader" action="http://empirical.cs.creighton.edu/~davereed/upload.php" enctype="multipart/form-data" method="post"> Select file for uploading: <input type="file" name="userfile"> <br /><br /> <input type="submit" value="Upload File"> </form> </body> </html>
  • 13. PHP file manipulations 13  <?php  $BASEDIR = "/var/www/davereed/files/";  if (!file_exists($BASEDIR.$_FILES['userfile']['name'])) {  move_uploaded_file($_FILES['userfile']['tmp_name'],  $BASEDIR.$_FILES['userfile']['name']);  print("File uploaded successfully");  }  else {  print("File already exists - no upload performed.");  }  ?> PHP provides extensive support for file/directory manipulation $_FILES[$FORM_ELE_NAME]['name'] original name of the file uploaded via the specified form input element $_FILES[$FORM_ELE_NAME]['tmp_name'] temporary name of the file where it is uploaded onto the server move_uploaded_file($_FILES[$FORM_ELE_NAME]['tmp_name'], $FILE_PATH_NAME) copies uploaded file to specified loc.
  • 14. Robust file uploading <html> <head> <title>Simple File Uploader</title> </head> <body> <form name="uploader" action="http://empirical.cs.creighton.edu/~davereed/upload.php" enctype="multipart/form-data" method="post"> <table> <tr><td>Enter your user name: <td><input type="text" name="userID" size=10 value=""> <tr><td>Select file for uploading: <td><input type="file" name="userfile"> </table> <input type="submit" value="Upload File"> </form> </body> </html> 14 could utilize other PHP features to make file uploading more robust  allow multiple students to submit same assignment  each student specifies a user name, file is uploaded into a subdirectory
  • 15. Robust file uploading 15  <?php  $userID = $_POST['userID'];  $BASEDIR = "/var/www/davereed/files/";  $_FILES['userfile']['name'] = explode(' ', $_FILES['userfile']['name']);  $_FILES['userfile']['name'] = implode('_', $_FILES['userfile']['name']);  if (IsSet($userID)) {  $BASEDIR = $BASEDIR.$userID."/";  if (!file_exists($BASEDIR)) {  mkdir($BASEDIR, 755);  }  }  if (!file_exists($BASEDIR.$_FILES['userfile']['name'])) {  move_uploaded_file($_FILES['userfile']['tmp_name'],  $BASEDIR.$_FILES['userfile']['name']);  print("File uploaded successfully");  }  else {  print("File already exists - no upload performed.");  }  ?> get the user ID from text box replace ' ' with '_' in file name if user ID is entered, extend path & create directory if deosn't already exist
  • 16. Homework submission program 16  Joel van Brandwijk has extended this program to create a generic homework submission utility  student interface is password driven  connects with Active Directory to verify password for given user name  student can select among current classes and assignments  course/assignment info is stored in an SQL database, accessed via PHP  student can specify multiple files, even structure into subdirectories for uploading  instructor interface is also password driven  checks database to make sure a legit instructor, then checks password  instructor can add/remove class, add/remove students, add/remove assignments  info is stored in SQL database, accessed via PHP  instructor can download submissions to local computer for grading empirical.cs.creighton.edu/submissions
  • 17. Example: email redirection 17 most Web sites give visitor option of sending feedback  can be accomplished using mailto: link <a href=mailto:[email protected]>Feedback?</a> potential problem: not all client computers are email-enabled  can instead use a PHP program as a front-end for email  user enters address, subject, message  PHP program receives & bundles these pieces into an email message, sends on  if desired, can be used for anonymous email redirection (no return address supplied)
  • 18. Example: email redirection <?php function show_form($email="",$message="",$subject="") { ?> <h2>Send Me an E-mail</h2> <form action="http://empirical.cs.creighton.edu/~davereed/email.php"  method="post"> Your E-mail address:<br> <input type=text name=email size=30 value="<?php print($email); ?>"><br> The Subject:<br> <input type=text name=subject size=30 value="<?php print($subject); ?>"><br> Your Message:<br> <textarea rows=10 cols=50 name=message><?php print($message); ?></textarea><br> <input type=submit value="Send E-mail"> </form> <?php } . . . 18 this part of the page defines a function for generating the input page
  • 19. Example: email redirection (cont.) 19  $email = $_POST['email'];  $subject = $_POST['subject'];  $message = $_POST['message'];  if (!isset($email) or !isset($message)) {  show_form();  }  else {  if (empty($message)) {  print("Please write something and resend.");  show_form($email,$message,$subject);  }  else {  if (empty($email)) {  $email="anonymous";  }  if (empty($subject)) {  $subject="stuff";  }  $sent = mail( "[email protected]", $subject, $message, "From: $email" );  if ($sent) {  print("<H1>Your Message Has Been Sent.</H1>");  }  else {  print("<p>The server was unable to send your mail.");  }  }  }  ?> if no inputs to page (not called from form), show input page if message field is empty, warn user and show the input page again if email or subject fields are empty, give default values send the email message and report status