Skip to content

Latest commit

 

History

History
1456 lines (1153 loc) · 30.3 KB

feb-2017.md

File metadata and controls

1456 lines (1153 loc) · 30.3 KB

PHP I Course Notes -- Feb 2017

##Mon 6 Feb 2017 http://collabedit.com/ydwmd

  • Q: How do you disable PHP display of errors?
  • A: ini_set('display_errors', 0);
//  examples of interpolation, concatenation and sprintf()
<?php
$href     = 'http://www.example.com';
$title    = 'An example link in PHP';
$contents = 'Example Link';
$link     = "<a href=\"$href\" title='$title'>$contents</a>";

echo $link;
echo PHP_EOL;

//  with concatenation
$link     = '<a href="' . $href . '" title="' . $title . '">' . $contents . '</a>';
echo $link;
echo PHP_EOL;

//  with sprintf()
$link     = sprintf('<a href="%s" title="%s">%s</a>', $href, $title, $contents);
echo $link;
echo PHP_EOL;
  • PHP 7 examples using unicode escape syntax
    • https:// github.com/dbierer/php7_examples/blob/master/php_7_0/unicode_escape_point_syntax.php
<?php
//  M2Ex2 -- Ebenezer

something { //  I am a parent
                { //  I am a child
                    //  some code
                }something else 
                
                {
                 // morecode
                }
}

//  another possible option
something
{ //  I am a parent
    { //  I am a child
        //  some code
    } something else {
        // morecode
    }
}

//  M2Ex3 -- Mark
function formatStatus($status) {
    $validValues = getStatusCodes();
    if (in_array(strtolower($status), $validValues)) {
        return strtolower($status);
    } else {
        return false;
    }
}

//  M2Ex3 -- Randy

$foo = 'variable';
echo "Here is a string with a $foo in it";
echo "Here is a string without a variable";
echo 'Here is a string without a variable';
echo 'Here is a string with $foo in it that may not do what you expect';


// "Here is a string with a variable in it"
// "Here is a string without a variable"
// 'Here is a string without a variable'
// 'Here is a string with $foo in it that may not do what you expect'

/* actual output directly from PHP
Here is a string with a variable in itHere is a string without a variableHere is
 a string without a variableHere is a string with $foo in it that may not do wha
t you expectPress any key to continue . . .
*/

//  M2Ex5 -- Roland

$name = 'Susie';
echo '1. my name is Susie <br />';
echo "2. my name is $name <br />";
echo "3. my name is ${name} <br />";
echo "4. my name is " . $name . "<br />";
echo '5. my name is $name <br />';

/*
1. my name is Susie
2. my name is Susie
3. my name is Susie
4. my name is Susie
5. my name is $name
*/

##Wed 8 Feb 2017 http://collabedit.com/vekec

<?php
//  string is perhaps more than what you would expect
$image = file_get_contents('default.png');
var_dump(base64_encode($image));
//  to reverse make sure you do base64_decode(xxxx)
<?php
//  example of type juggling
$amount = 99.99;
$name   = 'Fred';
echo $name . ' owes this much money: ' . $amount;

//  example of forcing data type in advance
$amount = (string) 99.99;
var_dump($amount);

//  example showing where last operation influences data type
$amount = 3 + 5 . 22;
var_dump($amount);

//  example showing where last operation influences data type
$amount = 3 + 5 + '22';
var_dump($amount);
<?php

//  shows proper usage of '=' vs. '=='
$a = 22;
$b = 33;
if ($a = $b) {
    echo 'Values Match';
} else {
    echo 'Values Do Not Match';
}
echo PHP_EOL;

$a = 22;
$b = 33;
if ($a == $b) {
    echo 'Values Match';
} else {
    echo 'Values Do Not Match';
}
echo PHP_EOL;
<?php
//  M2Ex4 -- Hello World

echo 'Hello World';

//  M2Ex5 -- Ebenezer

/*
Data Type: int, float, bool, string

True            //  boolean
'Hello World' // string
23  // int
867.54 // float
'false' // string
"867.54" // string
0   //  int
"Laugh often" // string
*/

//  M2Ex6 -- Mark

$noParentheses = 2 * 3 + 5;
$parentheses   = 2 * (3 + 5);

echo $noParentheses; //  11
echo $parentheses;   //  16


//  M2Ex7 -- Randy

$variableOne = ( 7 + 3 ) * 6; //  60
echo $variableOne;
echo PHP_EOL;

$variableTwo = 100 / ( 4 * 5 ); //  5
echo $variableTwo;
echo PHP_EOL;

//  $variableThree = 7 + ( ( 5 * ( 9 / 2 )) + ( 4 + 6) ); // 79.5
$variableThree = 7 + ( 5 * ( 9 / 2 ) + ( 4 + 6) ); // 79.5
echo $variableThree;
echo PHP_EOL;

##10 Feb 2017 http://collabedit.com/fna5w

<?php
//  homework over the weekend M3Ex*

define('INVALID_VALUE', 'This value is not acceptable');

$value = 0;

if ($value < 100) {
    echo INVALID_VALUE;
} elseif ($value > 1000) {
    echo INVALID_VALUE;
} else {
    //  continue with the program
}

//  this way works but is not a great idea
$value = 0;

if ($value < 100) {
    echo 'This value is not acceptable';
} elseif ($value > 1000) {
    echo 'This value is not acceptable';
} else {
    //  continue with the program
}
<?php
//  array example

$days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
var_dump($days);
echo PHP_EOL;
echo 'Today is ' . $days[4];
echo PHP_EOL;
echo 'The key for "Friday" is ' . array_search('Friday', $days);
echo PHP_EOL;

//  example of an "associative array"

$info = [
    'first'   => 'Fred',
    'last'    => 'Flintstone',
    'address' => '222 Rocky Way',
    'city'    => 'Bedrock',
    'zip'     => '000000'
];

echo $info['first'] . ' ' . $info['last'];
echo PHP_EOL;
<?php
//  result of a database query example:

$query_results = [
   0 => ['name' => 'fred', 'balance' => 99.99],
   1 => ['name' => 'joe', 'balance' => 88.88],
   3 => ['name' => 'susie', 'balance' => 77.77]
];
<?php
//  asort() retains keys

$days = [
    'mon' => 'Monday', 
    'tue' => 'Tuesday', 
    'wed' => 'Wednesday', 
    'thu' => 'Thursday', 
    'fri' => 'Friday', 
    'sat' => 'Saturday', 
    'sun' => 'Sunday'
];

var_dump($days);
echo PHP_EOL;
asort($days);
var_dump($days);


//  M2Ex7

$variableOne = ( 7 + 3 ) * 6;
echo $variableOne;
echo PHP_EOL;

$variableTwo = 100 / ( 4 * 5 );
echo $variableTwo;
echo PHP_EOL;

$variableThree = 7 + ( 5 * ( 9 / 2 ) + ( 4 + 6) );
echo $variableThree;
echo PHP_EOL;

/* Actual Output:
60
5
39.5
*/

//  M2Ex8 -- Randy //  ans: 3

$valueA = 1;
$valueB = 2;
$valueA += $valueB;
echo $valueA;

//  M2Ex9 -- Mark
<?php
$valueA = 'This is a ';
$valueB = 'combined string.';
echo $valueA . $variableTwo;
echo PHP_EOL;    

$valueA = 'This is a ';
$valueB = 'combined string.';
echo $valueA . $valueB;
echo PHP_EOL; 

/*
 * Actual Output:
PHP Notice:  Undefined variable: variableTwo in D:\www\php_exp\test.php on line 6

Notice: Undefined variable: variableTwo in D:\www\php_exp\test.php on line 6
This is a
This is a combined string.
*/    

//  M2Ex10 -- Ebenezer

$variableOne = 7 % 3;
echo $variableOne; // 1

$variableTwo = 0 % 3;
echo $variableTwo;// 0

$variableThree = 1 % 3;
echo $variableThree;// 1

##Mon 13 Feb 2017 http://collabedit.com/hv9q3

<?php
//  example of if
$today = date('l');
echo 'It\'s ' . $today;
echo PHP_EOL;
if ($today == 'Friday') {
    echo 'Tomorrow is the weekend in some parts of the world';
} else {
    echo 'Get back to work!';
}
<?php
//  example of if / else

//  simulates value coming from a form posting
$value = -22;       
$total = 0;
$error = false;

if ($value >= 0) {
    echo 'Amount added to total';
    $total += $value;
} else {
    echo 'Invalid Value!!!';
    $error = true;
}
echo PHP_EOL;

//  sometime later in the program
//  check the error flag and take action of some sort
<?php
//  example of if / elseif / else

$today = date('l');
$location = 2;
if ($today == 'Friday' && $location == 1) {
    echo 'Tomorrow is the weekend in your location';
} elseif ($today == 'Thursday' && $location == 2) {
    echo 'Tomorrow is the weekend in your location';
} else {
    echo 'Get back to work';
}
echo PHP_EOL;
echo 'It\'s ' . $today;
echo PHP_EOL;
<?php
//  ternary

define('DEFAULT_VALUE', 0);
$value = '<script>some.very.bad.javascript.by.an.attacher</script>';
if (ctype_digit($value)) {
    //  accept the value
    //  don't need to do anything!
} else {
    //  set to the default
    $value = DEFAULT_VALUE;
}

//  same thing but as ternary operation
$value = (ctype_digit($value)) ? $value : DEFAULT_VALUE;
<?php
//  example of null coalesce vs. ternary in web form
//  only for php 7+
define('DEFAULT_NAME', 'unknown');
$first = $_GET['first'] ?? $_POST['first'] ?? DEFAULT_NAME;
$last =  $_GET['last'] ?? $_POST['last'] ?? DEFAULT_NAME;
//  strip_tags() is a function which safeguards input
$first = strip_tags($first);
$last = strip_tags($last);
//  htmlspecialchars() safeguards output
echo htmlspecialchars($first . ' ' . $last);

//  for PHP 5:
$first = (isset($_GET['first'])) ? strip_tags($_GET['first']) : DEFAULT_NAME;
$last =  (isset($_GET['last'])) ? strip_tags($_POST['last']) : DEFAULT_NAME;

//  NOTE: use unset($variable) to wipe out variable + free memory

//  M3Ex1 -- Zaid
//  ans: camelCase variables
$variableOne = $variableOne + 1;
$variableOne += 1;  //  2

$variableTwo == $variableTwo;
$variableTwo !== $variableTwo;

$firstName = 'Alan';
$lastName  = 'Smith';

//  M3Ex2 -- Shawn

$variableOne = 5;
$variableTwo = "2day";

//  math operator
echo $variableOne + $variableTwo;

//  string operator
echo $variableOne . $variableTwo;

//  output: 752day

//  M3Ex3 -- Roland

define ( 'TEST', 'This is a test');
echo TEST . '<br>'; // This is a test<br>
echo test . '<br>'; // test<br>
    
//  M3Ex4: Randy

// Is it possible to define a case-insensitive constant name in PHP? If yes, give an example; if no, explain why not.    
// Yes
// Add true to third argument
//  example:
define ( 'TEST', 'This is a test', true);
echo TEST . '<br>'; // This is a test<br>
echo test . '<br>'; // This is a test<br>

//  M3Ex5: Mark

// Declare an array that contains the following sentence with one word in each array element: Programming in PHP is fun!
// Then, output the third element.

$sentence = ['Programming', 'in', 'PHP', 'is', 'fun'];

echo $sentence[2];
// Output PHP

//  M3Ex6: Zaid  echo $months['October'][1];

// What is the code to output the Tuesday in October?

$days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Friday'];
$months = [ 'January'   => $days,
            'February'  => $days,
            'March'     => $days,
            'April'     => $days,
            'May'       => $days,
            'June'      => $days,
            'July'      => $days,
            'August'    => $days,
            'September' => $days,
            'October'   => $days,
            'November'  => $days,
            'December'  => $days //  The last comma can included or removed
          ];

//  M3Ex7: Orders Array: Shawn
// What is the output of this script?
//  Bob Builder
$orders = [
    [
        'id' => 1,
        'orderStatus' => 'complete',
        'amount' => 560,
        'description' => 'Printer',
        'customerName' => 'Susie Builder',
        'formattedDate' => 'Dec 14, 1963'],
    [
        'id' => 2,
        'orderStatus' => 'invoiced',
        'amount' => 9800,
        'description' => 'Networking',
        'customerName' => 'Bob Builder',
        'formattedDate' => 'Jun 14, 1961']
];

echo $orders[1]['customerName'];

//  M3Ex8: Roland
// What is the key for 'long'?
// echo $geo[7];
// What is the key for 'North America'?
// echo $geo[8];

$geo = ['country' => 'USA',
    6 => 47.005,
    'long',
    5 => 'eagle'];
$geo[] = 'North America';

//  M3Ex9 Exercise: Randy
// Create a multi-dimensional array to hold the cards and numbers indicated below. Be as code efficient as you can.
// Use colors as the primary array key
// Output one color and card number

// (red, blue, green, yellow)
// (1, 2, 3, 4)

$cards = [1,2,3,4];
$suit =   
        [
            'red' => $cards,
            'blue' => $cards,
            'green' => $cards,
            'yellow' => $cards
        ];
echo $suit['green'][2];


//  homework for Wednesday

//  M4Ex1: Exercise
// What is missing from the following code?, and

// What is necessary to fix it?


if ( $valueA > $valueB )
    echo "Value A is greater than Value B";
    $valueB = $valueA;
    echo "The value for Value B has been changed";
    
    
//  M4Ex2: Exercise
// What is the output from each if/else construct?


$valueA = "50";
$valueB = 50;

if ( $valueA == $valueB ) {
    echo "Equal <br>";
} else {
    echo "Not equal <br>";
}

if ( $valueA === $valueB ) {
    echo "Identical <br>";
} else {
    echo "Not identical <br>";
}
    
//  M4Ex3: Exercise
// What is the output from each if/else construct?


$valueA = 10;
$valueB = 20;

if ( ( $valueA >= 50 ) xor ( $valueB === '20') ) {
    echo "Apples <br>";
} else {
    echo "Oranges <br>";
}

if ( ( $valueA >= '5' ) xor ( $valueB === 20 ) ) {
    echo "White <br>";
} else {
    echo "Black <br>";
}
    
//  M4Ex4: Exercise
// What is necessary to make this if statement into an if-else statement?


if ( $dayOfWeek === "Friday" ) {
    echo "See you on Monday <br>";
}

//  M4Ex5: Exercise
// Assume that people work in an office from Monday through Friday, and are off work on Saturday and Sunday.

// Modify the code below to handle the response if the day is either Saturday or Sunday?


$dayOfWeek = "Monday";

if ( $dayOfWeek === "Friday" ) {
    echo "See you on Monday";
} else {
    echo "See you tomorrow";
}

##Wed 15 Feb 2017 http://collabedit.com/xn249

<?php
//  code examples from our class discussion
$months = ['jan' => 'January', 'feb' => 'February', 'mar' => 'March' ];
//  or you an use array()
//  $months = array('jan' => 'January', 'feb' => 'February', 'mar' => 'March');

//  foreach example
foreach ($months as $item) {
    echo $item . ' | ';
}
echo PHP_EOL;
 
foreach ($months as $key => $item) {
    echo $key  . ':' . $item . ' | ';
}
echo PHP_EOL;

$array = [1.1, 2.2, 3.3, 4.4 ];
$output = '';
foreach ( $array as $key => $value ) {
    // store the new value back into the array
    $array[$key] = $value * 1.1;
    $output .= $array[$key] . '<br>' . PHP_EOL;
}

echo $output;
//  echo implode('<br>' . PHP_EOL, $array);
echo PHP_EOL;
<?php
//  example of while() using time() as a test

//  time() returns the # of seconds since 1 Jan 1970
$start = time(); 
$end = $start + 5;
$current = $start;
$i = 1;
while ($current < $end) {
    //  perform operations in the next 30 seconds
    echo 'Help! ' . $i++;
    $current = time();
}

echo $start . ':' . $current;
<?php

for ( $i = 0; $i <= 5; $i++) {
    if ($i === 3) continue;
    echo "The  number is $i <br />\n";
}

//  same thing but not using continue
for ( $i = 0; $i <= 5; $i++) {
    if ($i !== 3) {
        echo "The  number is $i <br />\n";
    }
}


//  M4Ex1: Exercise -- Zaid
// What is missing from the following code?, and

// What is necessary to fix it?

if ( $valueA > $valueB ) { //  this was missing!
    echo "Value A is greater than Value B";
}
$valueB = $valueA;
echo "The value for Value B has been changed";

  
//  M4Ex2: Exercise -- shawn
// What is the output from each if/else construct?


//  exercise has quotes on next line
$valueA = "50";
$valueB = 50;

if ( $valueA == $valueB ) {
    echo "Equal <br>";
} else {
    echo "Not equal <br>";
}

if ( $valueA === $valueB ) {
    echo "Identical <br>";
} else {
    echo "Not identical <br>";
}

//  actual output: Equal &lt;br&gt;Not identical &lt;br&gt;
    
//  M4Ex3: Exercise
// What is the output from each if/else construct?


$valueA = 10;
$valueB = 20;

if ( ( $valueA >= 50 ) xor ( $valueB === '20') ) {
    echo "Apples <br>";
} else {
    echo "Oranges <br>";
}

// xor: true if either $valueA or $valueB is true, but not both.
// $valueA is false, $valueB is false
// Oranges

if ( ( $valueA >= '5' ) xor ( $valueB === 20 ) ) {
    echo "White <br>";
} else {
    echo "Black <br>";
}
// $valueA is true, $valueB is true
// Black


    
//  M4Ex4: Exercise -- Randy
// What is necessary to make this if statement into an if-else statement?


if ( $dayOfWeek === "Friday" ) {
    echo "See you on Monday <br>";
} else{
    echo "generic fallback statement.";
}

//  M4Ex5: Exercise -- Mark
// Assume that people work in an office from Monday through Friday, and are off work on Saturday and Sunday.

// Modify the code below to handle the response if the day is either Saturday or Sunday?
<?php

//  '' 

$dayOfWeek = 'Saturday';

//  this is one possibility
if ( $dayOfWeek === 'Friday' ) {
    echo 'See you on Monday';
} else if( $dayOfWeek === 'Saturday'){ 
    echo 'Off work tomorrow';
} else {
    echo 'See you tomorrow';
}
echo PHP_EOL;

//  another solution
if ( $dayOfWeek === 'Friday' || $dayOfWeek === 'Saturday'){ 
    echo 'See you Monday';
} else {
    echo 'See you tomorrow';
}
echo PHP_EOL;

//  yet another solution
if ( in_array($dayOfWeek, ['Friday', 'Saturday'])){ 
    echo 'See you Monday';
} else {
    echo 'See you tomorrow';
}
echo PHP_EOL;

//  yet again another solution
switch ($dayOfWeek) { 
    case 'Friday' :
    case 'Saturday' :
        echo 'See you Monday';
        break;
    default :
        echo 'See you tomorrow';
}
echo PHP_EOL;

//  yet another solution yet again
echo (in_array($dayOfWeek, ['Friday', 'Saturday'])) ? 'See you Monday' : 'See you tomorrow';
echo PHP_EOL;
<?php
//  homework for Friday
// M4Ex6: Conditionals -- Zaid
// Write a switch construct that evaluates multiple cases against a true boolean, and acts upon one of them.

$color = 'White';
switch (true) {
    case $color == 'Green':
        echo 'color is Green';
        break;
    case $color == 'White':
        echo 'color is White';
        break;
    case $color == 'Black':
        echo 'color is Black';
        break;
    default: 
        echo 'The color is nothing';
}
echo PHP_EOL;

//  this is probably what you would really do
switch ($color) {
    case 'Green':
        echo 'color is Green';
        break;
    case 'White':
        echo 'color is White';
        break;
    case 'Black':
        echo 'color is Black';
        break;
    default: 
        echo 'The color is nothing';
}
echo PHP_EOL;

//  another example of switch() with unrelated items
$date = date('Y-m-d H:i:s');
$flag = 'XYZ';
$amount = 99.99;

switch (true) {
    case substr($date, 0, 4) == 2017 :
        echo 'do something with the date';
        break;
    case $flag == 'ABC':
        echo 'Prior year transaction detected and ABC flag is set';
        break;
    case $amount < 100:
        echo 'Prior year transaction detected and insufficient funds';
        break;
    default: 
        echo 'Have a good day';
}
echo PHP_EOL;
<?php
// M4Ex7: Exercise -- Shawn
//  suggestion: look up an earlier lab which defines this array to save time
/*
Build a card deck with the four colors representing suits, and four cards 1-4.
Iterate the card deck using a foreach loop, using keys and values.
Conditionally test for a suit and card of choice and build an output string.
Echo the output.
Here are the deck components:
*/


$output = '';
$cards = [1,2,3,4];
$deck = [
    'red' => $cards,
    'blue' => $cards,
    'green' => $cards,
    'yellow' => $cards
];

foreach($deck as $suit => $card) {
  if($suit === 'green') {
      $output .= $suit;
      $output .= (in_array(4, $card)) ? $card[array_search(4, $card)] : '';
      /*
      foreach($cards as $card) {
         if($card == 4) {
             $output .= $card; 
         }
      } 
      */
  }
}
echo $output;

// colors: red, blue, green, and yellow
// numbers: 1, 2, 3, 4
<?php
// M4Ex8: for Loop -- Roland
// What does this code do?
//  suggestion: run the code!!!
// gives prime numbers between 1 and 100

$max = 100;
echo '1, 2, 3, ';
//  no point in starting below 5 as 4 is not a prime
for ($x = 5; $x < $max; $x++)
{
    //  checks to see if number is odd or even
    //  this is a bitwise AND which === TRUE if odd number
    if($x & 1) {
        $test = TRUE;
        //  starts at 3; dont start at 1 because all numbers are divisble by 1
        //  no point in starting $i at 2 because we already know its not even
        for($i = 3; $i < $x; $i++) {
            //  if this is 0 then we know this number is not prime
            if(($x % $i) === 0) {
                $test = FALSE;
                break;
            }
        }
        if ($test) echo $x . ', ';
    }
}


// M4Ex9: Exercise -- Randy
// How is this code different from that used in the for statement?
// Uses while instead of for

$i = 1;

while ($i <= 5) {
    echo $i . "Hello World!\n";
    $i++;
}


// M4Ex10: Exercise -- Mark
// Write a do...while loop construct that decrements a count value of 6 for customer James Dean.

$number = 6;

do {
    echo PHP_EOL . $number;
    $number--;
} while ($number >= 0);


// M4Ex11: Exercise -- Ebenezer
// What is the output?

$i = 6;

while ( $i > 0 ) {
    if ( $i === 4 ) break;
        echo "You only have $i chance(s) to get this right!<br>";
        $i--;
    }
}
//  first you need to get rid of the extra }
// you only have 6 chances to get this right
// you only have 5 chances to get this right, code stops at 4 i guess
    
    
// M4Ex12: Looping  -- Ebenezer
// Write code to count from 1 to 10 using each type of loop:

// for
for ($i = 1; $i >= 10; $i++) 
{ 
    echo "$i <br>"; 
} 

// while
$i = 1; 
while ($i <= 10)
{ 
    echo "$i <br>"; 
    $i++;
} 

// do-while
$i = 1; 
do { 
    echo "value of $i is 5.<br>"; 
    $i++; 
} 
while ($i <= 10);

##17 Feb 2017 http://collabedit.com/aycay

<?php
//  homework for monday

// M5Ex1: Function Calling -- Ebenezer
// Create a script that defines a function named getOrderTotal ($num1, $num2), which takes two arguments and returns the sum.
// Call the function and output the result.

function getOrderTotal($num1, $num2)
{
     return $num1 + $num2;
}
 
$bill = getOrderTotal(5,8);
 
var_dump($bill);
 

// M5Ex2: Recursive Function Exercise -- Mark
// The Fibonacci sequence is a series of numbers in which each number is the sum of the previous two numbers, starting with 0.

// 0, 1, 1, 2, 3, 5, 8, 13, 21, 34

// Write a function that returns the nth number in a Fibbonacci sequence.

function fibonacci ($nth) {
    $num1 = 0;
    $num2 = 1;
    for ($i = 1, $I < $nth, $I++ ) {
        $sum = $num1 + $num2;   // adds num1 and 2 to sum    
        $num1 = $num2;          // copies num2 to num1
        $num2 = $sum;           // copies sum to num 2
    }
    return $num1;                   // return num1
}

echo fibonacci(4);   // output 2
    

// M5Ex3: Exercise -- Randy
// Notice the variable $varA has the same name inside and outside of the function.

$varA = 1;
function myTestFunction()
{
    $varA = 2;
    return $varA;
}

//  call the function
echo myTestFunction();
//  echoes the value of $varA inside the function scope

echo $varA;
// What is the return value of the call line? //  2

// What is the echoed value on the last line? //  1


// M5Ex4: Exercise -- Roland
// Build two functions, one to get an array element of configuration, and one that takes an array and builds an HTML select/option list.

//  contents of config.txt
return [
  'status_options' => [
  'en' => 'English',
  'es' => 'Espanol',
  'fr' => 'francais',
  ],
];

define('CONFIG_FILE', 'config.txt');

//  Starting Code
function getConfig($configFile, $config_key)
{
    $config = include __DIR__ . '/' . $configFile;
    return $config[$config_key];
}

function htmlSelectHtml( $config )
{
    $html = '<select>';
    //  loop through key / value pairs to create <option> tags            ...
    foreach ($config as $key => $value) {
        $html .= '<option value="'. $key . '">' . $value . '</option>';
    }
    $html .= '</select>';
    return $html;
}

$config = getConfig(CONFIG_FILE, 'status_options'); //  returns an array of allowed statuses
echo '<form method="get">';
echo htmlSelectHtml($config); //  returns a string contains an HTML <select> element with the status options.
echo '</form>';

##Weds 22 Feb 2017 http://collabedit.com/43fpw

<?php
// M6Ex1: Exercise -- Zaid
// Write an example of:
/*
Open a file with error handling
Write something to the file
Close the file
*/
$fileName = 'Sometext.txt';
$fh = fopen($fileName, 'a');
if(!$fh) exit { ('File can\'t open');
fwrite($fh, 'I want to let you know that i can do this');
fclose($fn);
<?php
/*
M6Ex2: Exercise -- Shawn
Using file_get_contents(), get the contents of a file
Display the result
*/

echo file_get_contents('/ws/counter.txt');
<?php
/*
M6Ex3: Exercise -- Roland
Using file_put_contents(), create some string content. --
Over write the contents of a file.
Test and echo for success.
*/

//answer
$file = 'test.txt';
$someStringContent = "some string content";
echo file_put_contents($file,$someStringContent);
<?php
/*
M6Ex4: Exercise -- Randy
Write an array of text strings to a file.
Open the file using fopen().
read and output the third character from each line.
*/

$animals = ['cow','pig','horse','chicken'];

foreach($animals as $animal){
    file_put_contents('animals.txt', $animal . PHP_EOL, FILE_APPEND);
}
$readText = file('animals.txt');
foreach($readText as $text){
    
    echo $text[2];
}
<?php
//Mark

$file = __DIR__ . '/people.txt';

$arr = ['Hello ', 'everyone ', 'in ', 'class ', 'today '];

$writeToFile = file_put_contents($file, $arr);

function eachLine($file)
{
    $resource = fopen($file, 'r');
    $f = fread($resource, 1024);
    $arr = explode(' ', $f);
    foreach($arr as $key => $value){
        echo $value[2] . PHP_EOL;
    }
    fclose($resource);
}

eachLine($file);
<?php
/*
M6Ex5: Exercise -- Ebenezer
Read the directories and files in the class project root and output the following:

File Name
File Size
Number of lines in the fileok
*/

//read all files in directory
foreach (glob('*') as $file){
    echo "File name: $file Size: "
        . filesize($file)
        . "Number of lines: " . count(file($file)) . PHP_EOL;
}

#Mon 27 Feb http://collabedit.com/njnxu

M7Ex1: Exercise
Build an standard HTML form with embeded PHP

Account for

form tag attributes
input tags for both username and password
dynamic attributes for each input tags
a submit button
Some starting code

//variable assignments as necessary
<form
// Additional tag attributes and inputs with embeded PHP
</form>
<!-- // Ebenezer -->
<?php $input = ['username','password'];?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="username">Username</label>
<input type="text" name="<?php echo $input[0];?>" value="">
<label for="password">Password</label>
<input type="password" name="<?php echo $input[1];?>" value="">
<input type="submit" name="submit" value="SEND HTML">
</form>
M7Ex2: Exercise
Only using PHP, build a simple login form.

Output the HTML to the browser

// Starting Code
$html = '<form';

// code …

$html .= '</form>';
<?php
// Mark
// this starts output buffering; buffer is auto-flushed upon program end
ob_start();
define('TITLE', 'Login page');

$header = '<h1>' . TITLE . '</h1>';

$form = '<form action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
$form .= '<div>';
$form .= '<label>Username</label>';
$form .= '<input type="text" name="username" />';
$form .= '</div>';
$form .= '<div>';
$form .= '<label>Password</label>';
$form .= '<input type="password" name="password" />';
$form .= '</div>';
$form .= '<input type="submit" value"Login" />';
$form .= '</form>';
echo $header . $form;
M7Ex3: Exercise
Use the code from M7Ex1 or Ex2
Create a script that takes input from a login form (username, password, and email address).
Filter and validate all inputs
Display a message for both invalid and valid input.
<?php
// Roland
// this starts output buffering; buffer is auto-flushed upon program end
ob_start();
define('TITLE', 'Login page');

$header = '<h1>' . TITLE . '</h1>';

$form = '<form action="' . $_SERVER['PHP_SELF'] . '" method="POST">';
$form .= '<div>';
$form .= '<label>Username</label>';
$form .= '<input type="text" name="username" />';
$form .= '</div>';
$form .= '<div>';
$form .= '<label>Password</label>';
$form .= '<input type="password" name="password" />';
$form .= '</div>';
$form .= '<input type="submit" name="submit" value"Login" />';
$form .= '</form>';
echo $header . $form;

// OR:
// if ($_SERVER['REQUEST_METHOD'] == 'post') {}
if (isset($_POST['submit'])) {
    
    // alt for php 5.6 and below (also works in PHP 7)
    $username = (isset($_POST['username'])) ? $_POST['username'] : '';
    // this works in PHP 7+
    $password = $_POST['password'] ?? '';
    $email = '[email protected]';
    
    
    //filter username
    if (ctype_alnum($username)) {
        echo htmlspecialchars("$username consists of all letters or digits.\n");
    } else {
        echo htmlspecialchars("$username does not consist of all letters or digits.\n");
    }
    
    //filter password
    if (strip_tags($password)) {
        echo "$password will work.\n";
    } else {
        echo "$password won't work.\n";
    }
    
    //filter email
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === true) {
        echo htmlspecialchars("$email is a valid email address");
    } else {
        echo htmlspecialchars("$email is not a valid email address");
    }
}
M7Ex4: Exercise
Update the email sanitizing script you wrote in a previous exercise, escaping the output.
<?php
// Zaid

$mail = '[email protected]'; 
if ( filter_var( $mail, FILTER_VALIDATE_EMAIL ))
{ 
echo htmlspecialchars($mail) . ' Clean it . <br/>'; 
}
else 
{ 
    echo htmlspecialchars($mail) . ' The mail is not valid . <br/>'; 
}

<?php
// Ebenezer
define('USERNAME','[email protected]');
define('PASSWORD','chicken');
if (isset($_POST['submit'])){
    //ensure we have a valid username, an email
    echo (filter_var($_POST['username'], FILTER_VALIDATE_EMAIL) && ($_POST['username'] == USERNAME && ($_POST['password'] == PASSWORD))) ? 'You are welcome': 'invalid username or pasword combination';
    
}
    
?>
<?php
// Database Example
$conn = mysqli_connect('127.0.0.1', 'root', 'vagrant', 'php1');
$result = mysqli_query($conn, "SELECT * FROM customers");
$row = mysqli_fetch_all($result, MYSQLI_ASSOC);
mysqli_close($conn);

echo '<pre>';
echo 'ALL rows';
var_dump($row);
echo PHP_EOL;
<?php
// OR
ob_start();
echo '<pre>';
echo 'ONE row at a time';
echo PHP_EOL;
$conn = mysqli_connect('127.0.0.1', 'vagrant', 'vagrant', 'course');
$result = mysqli_query($conn, "SELECT * FROM customers");
while ($row = mysqli_fetch_assoc($result)) {
    var_dump($row);
    echo PHP_EOL;
}
mysqli_close($conn);
echo '</pre>';