Lecture 7 Log into Linux client or into csserver directly webspace

advertisement
Lecture 7
●
●
Log into Linux client or into csserver directly
Change to subdirectory cs350/pizza in
webspace
●
cp ~hwang/cs350/lecture07/*.* .
●
Load pizza-v3.php into a text editor
●
Browse to
http://csserver.evansville.edu/~username/cs350/
pizza/pizza-v3.php
September 19, 2014
CS 350 - Computer/Human Interaction
1
Outline
●
PHP
●
References: PINT, PW3S, PWIZ
●
●
Project Overview and HTML5/PHP prototype
assignment posted to course webpage
Reminder: Refrigerator use interviews need to
be done by Tuesday's class. Bring all notes
from the in-class exercise as well as from the
out-of-class interviews.
September 19, 2014
CS 350 - Computer/Human Interaction
2
PHP
●
●
PHP is a portable (UNIX, Windows, Mac)
scripting language with C++-like syntax with
more high-level features than C++ especially
designed for web programming.
PHP was created by Rasmus Lerdorf in 1995 to
make common web programming tasks easier.
The name originally stood for "Personal Home
Page," but has since become to mean "PHP:
Hypertext Processor. PHP 5 is the current
version.
September 19, 2014
CS 350 - Computer/Human Interaction
3
Comments
●
PHP syntax basically is the union of C and shell
scripting. E.g. PHP comments are indicated
by //, #, or /* */.
// This is a comment
# This is a comment, too
/* This is multi-line
comment */
September 19, 2014
CS 350 - Computer/Human Interaction
4
Variables
●
●
●
As with shell scripts, PHP variables are not
declared and may change type through
assignment. Be careful of spelling errors.
PHP has seven data types: integer, float,
boolean, string, array, object, and resource.
However, PHP will do automatic conversion.
PHP variable names always start with $.
$msg = "Hello world!";
print "$msg\n"; // one string
echo $msg, "\n"; // list of items
September 19, 2014
CS 350 - Computer/Human Interaction
5
Constants
●
PHP constants are defined using the define
command. E.g.,
define ("SecondsPerDay", 86400);
echo SecondsPerDay, "\n";
●
●
Unlike variables, constant names do not start
with $. They also cannot be used inside "" 's.
There are several predefined constants. E.g.,
__FILE__, __LINE__ : the file and line being executed
M_PI, M_SQRT2 : pi and square root of 2
September 19, 2014
CS 350 - Computer/Human Interaction
6
Arrays
●
●
PHP has two types of arrays, indexed and
associative, created using the array
command. Unlike C++, the elements do not
need to be of the same type.
Indexed arrays are created and accessed as
follows:
$data = array(1,"abc",2.5);
echo $data[2], "\n"; // 2.5
●
Can add to an array using [] (array operator):
$data[] = $msg;
September 19, 2014
// $data[3]
CS 350 - Computer/Human Interaction
7
Arrays
●
Associative arrays are created and accessed
as follows:
$fruits = array("a"=>"apple",
"b"=>"banana",
"c"=>"cantaloupe");
echo $fruits["b"], "\n"; // banana
●
Use the array operator to add elements
$fruits["d"] = "date";
●
For both kinds of arrays, can start with an
empty one and just add elements.
September 19, 2014
CS 350 - Computer/Human Interaction
8
Operators
●
●
Arithmetic, equality, relational, and logical
operators are as in C++. In addition, there are
logical operators AND and OR.
=== (identity) can be used to check for
unwanted type conversions.
●
String concatenation is done using '.' E.g.,
$word1 = "hot";
$word2 = "dog";
$word3 = $word1 . $word2;
September 19, 2014
// "hotdog"
CS 350 - Computer/Human Interaction
9
String and Array Tricks
$line = "abc\ndef\nghijkl\nmnop";
$parts = explode("\n", $line);
// array of elements between separator
$size = count($parts);
// 4
$parts[] = "qrst";
// add to end
$partlist = implode(", ", $parts);
// string of elements with separator
$input = trim($input);
// remove leading/trailing whitespace
$input = rtrim($input);
// remove only trailing whitespace
September 19, 2014
CS 350 - Computer/Human Interaction
10
Here Documents
●
PHP has here documents. These are good for
when most of the text is static with a few places
with variables. Note the redirection operator is
<<< and there is a semicolon at the end.
print <<<EOT
<h1>$coursenumber - $coursetitle</h1>
<p>Class schedule: $days, $time, $room<br />
Final exam period: $fday, $ftime<br />
</p>
EOT;
September 19, 2014
CS 350 - Computer/Human Interaction
11
External Commands
●
Backticks (`) can be used to run external (OS)
commands.
$cwd = `pwd`;
print "Current directory is $cwd\n";
print "The files in the directory:\n";
print `ls`;
September 19, 2014
CS 350 - Computer/Human Interaction
12
Control Constructs
●
●
●
The if-else statement is
same as C++. Multi-branch
selection is if-elseifelse.
"" (empty string), "0", 0, 0.0
are false, but "0.0" is true.
All other values are true.
The switch statement is
same as C++ (including case
fall-through without a break
statement), but also can use
strings as case values.
September 19, 2014
●
●
PHP has while, do-while,
and for statements as in
C++.
PHP also has a foreach
statement for use with arrays.
foreach ($data as $item) {
print "$item\n";
}
foreach ($fruits as
$key => $fruit)
print "$key = $fruit\n";
}
CS 350 - Computer/Human Interaction
13
File Input
// Read entire file into one string
$filestring = file_get_contents ($filename);
if ($filestring)
print $filestring;
else
print "Could not open $filename\n";
// Read file line by line
$handle = fopen($filename, "r") // or "w","a"
OR die ("Cannot open $filename\n");
$line = fgets ($handle); // read first line
while (!feof($handle)) {
print "$line\n";
$line = fgets ($handle); // read next line
}
fclose ($handle);
September 19, 2014
CS 350 - Computer/Human Interaction
14
File Output
// Write out an array to a file
$outfile = fopen($filename, "a");
foreach ($array as $string)
$numbytes = fwrite ($outfile, "$string\n");
fclose ($outfile);
// Write out a string as the entire contents of file
$numbytes = file_put_contents($filename, $string);
// 3rd arg FILE_APPEND to append
September 19, 2014
CS 350 - Computer/Human Interaction
15
Remote Files
●
Since PHP was designed for use with web
servers, the fopen() command can be used
to access remote files by giving a URL instead
of a local file name.
$slash = fopen("http://www.slashdot.org", "r");
$site = fread($slash, 200000); // 1st 200K bytes
fclose($slash);
print $site;
September 19, 2014
CS 350 - Computer/Human Interaction
16
Functions
●
PHP functions are defined as in C++ without
the parameter types using the function
keyword. Has both value and reference
parameters.
function foo ($arg1, &$arg2) {
$result = ...; // local variable
...
return $result;
}
●
Function definitions can appear anywhere in
the script.
September 19, 2014
CS 350 - Computer/Human Interaction
17
Scoping Rules
●
●
●
●
In PHP, any variable not set inside a function is
considered global. That is, they are accessible
from anywhere else in the script, except inside
a function.
In particular, this means that variables span any
code islands in the script
Variables set inside functions are local to that
function.
Some installations may be set to warn about
undefined variables.
September 19, 2014
CS 350 - Computer/Human Interaction
18
Superglobal Variables
●
●
Special variables, called superglobals, are
accessible anywhere, including inside functions.
$_SERVER is a superglobal associative array
that gives access to information about the
webserver.
print "Server IP: $_SERVER['SERVER_ADDR']";
●
$GLOBALS is a superglobal associative array
that gives access to any global variable. The
name of the variable is the index.
September 19, 2014
CS 350 - Computer/Human Interaction
19
PHP Scripts
●
PHP scripts (called code islands) are
embedded within static text. The static text is
output verbatim by the PHP interpreter. E.g.
This is text before the first code island
<?php
print "This line is generated by code\n";
?>
This is text between code islands
<?php
print "This line is generated by code\n";
?>
This is text after both code islands
September 19, 2014
CS 350 - Computer/Human Interaction
20
PHP Webpages
●
●
●
Web servers run PHP webpages (extension
.php) through the PHP interpreter and serve
up the resulting standard output.
Since the static text is passed through
verbatim, most of a PHP webpage is just
regular HTML.
The places where you want server-side
dynamic creation of content are implemented
as PHP code islands.
September 19, 2014
CS 350 - Computer/Human Interaction
21
Example: Current Year
●
●
Instead of computing the current year on the
client side using JavaScript, we could compute
it on the server side using a PHP script.
The PHP script is in-lined where the result of
the script is needed.
September 19, 2014
CS 350 - Computer/Human Interaction
22
Example: Customizable List
●
●
We can use PHP to create customizable lists of
input. In a real application, this data would be
stored in a database. For this class, textfiles
will suffice.
The textfiles size-choices.txt and
topping-choices.txt contain data for
populating the PPP order form. We want to use
this data to create the size and toppings choice,
respectively.
September 19, 2014
CS 350 - Computer/Human Interaction
23
Example: Customizable Lists
●
●
In pizza-v3.php, we replace the hardcoded
HTML with PHP code islands that open the
appropriate file, read the data, and print out the
corresponding HTML.
Note that attribute values are in quotes, so the
output string needs to escape them or a here
document can be used.
September 19, 2014
CS 350 - Computer/Human Interaction
24
Review: HTML Forms
●
Syntax
<form action="URL" method="post">
<!-- form elements can only
appear in a form -->
</form>
where URL is the location of the CGI script to
run when the form is submitted.
September 19, 2014
CS 350 - Computer/Human Interaction
25
CGI Programs
●
●
CGI (Common Gateway Interface) programs
run on the web server. The program's standard
output is sent to the browser. CGI programs
are used to process web form data.
PHP processing is built into most (all?) web
servers, making it a convenient way to write
CGI programs.
September 19, 2014
CS 350 - Computer/Human Interaction
26
CGI Programs
●
●
●
When a form is posted, each form element's
data is sent as encoded "name=value" pairs
separated by &.
A CGI script receives this data as one long
string through standard input. CGI script must
decode the input data into a usable form.
After processing the data, a response page
must be sent by writing HTML code to standard
output.
September 19, 2014
CS 350 - Computer/Human Interaction
27
Form Values in PHP
●
Posted form input is processed automatically in
PHP and placed in the superglobal array
$_POST. This is an associative array with the
name attribute values as keys. Generally, it is a
good idea to copy the values into local
variables.
$name = $_POST['name'];
$size = $_POST['size'];
September 19, 2014
CS 350 - Computer/Human Interaction
28
HTML Functions
●
htmlspecialchars function encodes HTML
punctuation to prevent injections
$name = htmlspecialchars($_POST['name']);
●
nl2br function convert newlines into <br />.
Good when echoing textarea data
$address =
nl2br(htmlspecialchars($_POST['address']));
September 19, 2014
CS 350 - Computer/Human Interaction
29
Programming Notes
●
●
Errors in CGI PHP code execution are written to
standard output, so they show up in the response
page along with whatever HTML is rendered.
When a PHP webpage does not render at all,
there usually is a syntax error. The error
messages are put in the webserver error log. On
csserver this is
/var/log/apache2/error.log. (This file
generally is not readable by all, but we'll try to
keep it open manually.)
September 19, 2014
CS 350 - Computer/Human Interaction
30
Example: PPP Form
●
●
Generally form data is processed and stored in
a database. For this course, we will write data
to a world writable textfile. If you want to create
new files within a program, the enclosing
directory needs to be world writable as well.
For the PPP, create a textfile orders.txt and
make it world writable
$ touch orders.txt
$ chmod a+w orders.txt
September 19, 2014
CS 350 - Computer/Human Interaction
31
Example: PPP Form
●
pizza-cgi.php is most of a CGI program for
the PPP form. We need to add the following:
–
Store form data into local variables doing any
needed processing
–
Convert toppings array in to a comma-separated
string
–
Put data into the orders.txt file
–
Finish sending the response page
September 19, 2014
CS 350 - Computer/Human Interaction
32
Download