September 30 - ndgriffeth/Class-Notes-and-Lectures GitHub Wiki

Assignment for Wednesday October 2

  • Get together in a team of 2-3 people and decide on a PHP project that will require registration, logins, checkouts, and maintenance of data by the project.

  • (Preview) For Monday, October 7, create a form for registering on a Web site and save usernames and passwords of anyone who registers. Don't let anyone use the same username twice! Construct a Web interface that lets a site administrator view the usernames and passwords.

PHP Introduction (continued)

Reading: Chapter 1, PHP Crash Course

Using PHP and HTML together

PHP and HTML code can be interleaved (or not). The following two code segments do exactly the same thing:

 
Your name is:  
<?php  
$name = $_POST['name'];  
echo $name;  
?>   

and

  
<?php   
$name = $_POST['name'];  
echo "Your name is: ".$name;  
?>   

See string1.html/string1.php and string2.html/string2.php

Strings

Strings can be strung together with the "." operator (see above).

Strings can be delimited by either single or double quotes. If a variable appears inside a string delimited by double quotes, it is evaluated. See string3.html/string3.php and string4.html/string4.php

The following PHP code is the same as above:

<?php  
$name = $_POST['name'];  
echo "Your name is: $name";  
?>  

But this is not:

<?php  
$name = $_POST['name'];  
echo 'Your name is: $name';  
?>

Variable Review

  • Variable names start with a $
  • Except for variables defined inside functions, variable scope is global
  • User inputs appear in arrays whose names are:
    $_POST: for method="post"
    $_GET: for method="get"
    $_REQUEST: includes variables from both methods
  • The type of a variable is determined by its value and usage.
  • A variable may contain the name of a variable.

Control Structures

  • You can break out of a control structure with the "exit" statement.

Conditionals

  • if statements are C- or Java-style
  • except that there's an elseif:
if ($roomtype == "elite") {  
     $totalcost = ELITEPRICE*$seats; }  
elseif ($roomtype == "regular") {  
     $totalcost = REGULARPRICE*$seats; }  
elseif ($roomtype == "budget") {  
     $totalcost = BUDGETPRICE*$seats; }  
else { echo "Invalid room type"; exit; }    

For use of the above, see main1.php

Loops

  • "while" and "do...while" loops are C- or Java-style.
  • for loops are C- or Java-style.
  • There is a "foreach" loop! (See Chapter 3)
echo '<p>$_POST is: </p>';
foreach($_POST as $entry) {
   echo "<p>$entry</p>";
}

Exercise.

Write html and php to duplicate the following.

Here is a Web page containing a form:
Picture of a page

Here is the result of clicking the submit button:
Picture of a page

Reading and Writing Files

Reading: Chapter 2, Storing and Retrieving Data

File permissions in Unix

Reference: http://www.dartmouth.edu/~rc/help/faq/permissions.html

  • Three types of file users: user (u), group (g), and other (o).
  • Each type can have read permission (r), write permission (w), execute permission (x), or any combination.
  • Listing files in long format (ls -l) tells you what permissions users have for the files.
  1. The first field, positions 2-10, summarize the security status.
    1. The first three are user, next three are group, last three are other.
    2. They appear in order r, w, x. If a permission is not granted, the letter is -.
  2. The second field names the user that owns the file (usually, the account that created it).
  3. The third field names the group of the owner.

Example:

-rw-r--r--  1 nancyg  staff    286 Sep 25 13:37 README.md
-rw-r--r--@ 1 nancyg  staff  55973 Sep 24 15:52 Sept25Image1.jpg
-rw-r--r--@ 1 nancyg  staff  51725 Sep 24 16:33 Sept25Image2.jpg
-rw-r--r--@ 1 nancyg  staff  61732 Sep 24 16:56 Sept25Image3.jpg
-rw-r--r--@ 1 nancyg  staff  60748 Sep 24 19:25 Sept25Image4.jpg
-rw-r--r--  1 nancyg  staff    174 Sep 28 14:43 loop1.html
-rw-r--r--  1 nancyg  staff    258 Sep 28 14:45 loop1.php
  • "chmod" lets you change file permissions. Examples
  1. chmod o+x thisfile: let other execute the file.
  2. chmod g+w thatfile: let any group member write the file.
  3. chmod u+rwx publicfile: let the user (owner) read, write, and execute the file.
  4. chmod a+r worldreadable: let anyone read the file (i.e., make it world-readable).

Opening files

Function: resource fopen( string $filename, string $mode)
Reference: http://www.php.net/manual/en/function.fopen.php

  • $filename
  • Recommend putting it outside the Web document tree
  • $_SERVER['$DOCUMENT_ROOT'] is the document root; to put it outside, you can create a directory in $_SERVER['$DOCUMENT_ROOT']/.. (the parent of document root).
* $mode
  • r: read starting from beginning of file
  • w, a, or x: write (over-write), append (to end), and write (quit if file already exists)
  • b or t: binary (default) or text
* Returns a _resource_ . We put this in a variable to reference later; we won't manipulate it.

A problem opening a file most likely means permissions are wrong.

Reading Files

Functions:

  • string fgets ( resource $handle [, int $length ] )
    Reads a line, returns it in a string, from the file whose "fopen" returned $handle. (It stops at $length characters if the second argument is present.)
    Reference: http://www.php.net/manual/en/function.fgets.php.
    Other commands:
  1. [fgetss](http://www.php.net/manual/en/function.fgetss.php): reads a line into a string, strips tags.
  2. [fgetcsv](http://www.php.net/manual/en/function.fgetcsv.php): reads a line into an array, from a csv-formatted file.
  3. [fread](http://www.php.net/manual/en/function.fread.php): reads the entire file into a string, given a handle (file pointer).
  4. [file_get_contents](http://www.php.net/manual/en/function.file-get-contents.php): opens and reads the entire file (given the filename) into a string.
  5. [readfile](http://www.php.net/manual/en/function.readfile.php): opens and reads the file (given the filename), echoes it to standard out, and closes it. Example: testread1.php
  6. [fpassthru](http://www.php.net/manual/en/function.fpassthru.php): reads and outputs the file, given a handle (file pointer). Example: testread2.php
  7. [file](http://www.php.net/manual/en/function.file.php): opens and reads the file into an array (one line per array entry). Example: testread3.php
  8. [fgetc](http://www.php.net/manual/en/function.fgetc.php): reads the file one character at a time.

When reading a line or character at a time, you need to know when to stop:
Function: bool feof ( resource $handle )
Returns true if you have reached the end of file.

Writing Files

Functions:

  1. [file_put_contents](http://www.php.net/manual/en/function.file_put_contents.php): puts the entire contents of a string in a file, given the filename.

Closing Files

Function: bool fclose ( resource $handle )
Closes the designated file.
Reference: http://www.php.net/manual/en/function.fclose.php

Exercise

Write php programs similar to testread1.php, testread2.php, and testread3.php to demonstrate the differences between fgets, fgetss, and fgetcsv.

Arrays

Familiar

  • An array is a data structure with multiple entries.
  • An array can have one, two, or more dimensions.
  • Array entries can be accessed by position (or positions, if multi-dimensional). Indexing is zero-based: $myarray[0] is the first element of the array.
  • Regular (as opposed to ragged) multi-dimensional arrays are indexed as usual: $myarray[$i][$j]...
  • You can use an array entry such as $myarray[$i] anyplace you can use a variable.
  • Using loops to access an array:
for ($i=0; $i<10, $i++) {
    echo $myarray[$i];
}

Different

  • Associative addressing (like a dictionary in Python). Entries can be identified by keys rather than numeric indexes.
  • Array initialization
  1. Numeric indexes: $myarray = array('a', 'b', 'c');
  2. Associative: $myarray = array('a'=>0, 'b'=>0, 'c'=>0);
  3. Range operator: $myarray = range(1,10); Also:
    • range (10, 100, 2);
    • range ('a', 'z');
    • range ('a', 'z', 3);
* Using loops
  • [foreach](http://www.php.net/manual/en/control-structures.foreach.php)
        foreach ($myarray as $key=>$value) {
            echo $key."=>".$value."<br />";
        }
    
    See testarray1.php.
  • [each](http://www.php.net/manual/en/function.each.php)
        $myarray = range('a', 'z');
        while (list($key, $value) = each($myarray)) {
            echo $key." => ".$value."<br />";
        }
    
    See testarray2.php and testarray3.php.
* Types can be mixed in arrays. See testarrayshape1.php. * [Array operators](http://php.net/manual/en/language.operators.array.php)
  • + (union): combine two arrays, to include all entries from both arrays. If a key of the right-hand array matches a key of the left-hand array, include only the entry from the left-hand array. See testarray4.php and testarray5.php.
  • == (equals): true if the arrays have the same key/value pairs. See testarray6.php.

Review Questions

  1. Write a loop that reads through a file whose handle is $fp, one line at a time, and outputs "Contains a special character" if the line contains a special character and prints "Does not contain a special character" if it does not. Each line of the file should produce a line on the output html page.

  2. What mode do you use with fopen to:
    a. Open a file for adding more information to it (without erasing any)?
    b. Open a file for writing over the information in it?
    c. Open a file for reading?
    d. Operate on a file in a binary-safe manner?

  3. What does binary-safe mean when you are reading and writing files?

  4. What read and write operations do you use to read or write one line of a file at a time? How do you create a new line in a file using php?

  5. Write php code to initialize an array with entries:

Key Value
alpha 10
beta 1
gamma 100
and then loop through the table, outputting one line containing each key and value pair.
  1. Given an array $array1 with the above value and a second array $array2 with the following value:
Key Value
alpha 5
delta 7
beta 9
What does the statement
$array3 = $array1+$array2; 
do?
  1. Here's the code we did in class to read & print a file:
<?php

if (!$fp=@fopen("data", "r"))
{
	print("Try again later");
	exit;
}

while (!feof($fp)) {
	if (!$string=@fgets($fp))
	{
		print("Read error");
		exit;
	}
	list($user,$password) = explode(" ", $string);
	print ($user." ".$password."
"); } fclose($fp); ?>
⚠️ **GitHub.com Fallback** ⚠️