+ All Categories
Home > Documents > PHP Programming What we know so far… …and something new.

PHP Programming What we know so far… …and something new.

Date post: 21-Dec-2015
Category:
View: 215 times
Download: 0 times
Share this document with a friend
Popular Tags:
30
PHP Programming What we know so far… …and something new
Transcript
Page 1: PHP Programming What we know so far… …and something new.

PHP Programming

What we know so far…

…and something new

Page 2: PHP Programming What we know so far… …and something new.

Forms

• Creating a form in html:<form method="get" action="cooking.php">

<select name="day">

<option value="1">Monday/Wednesday

<option value="2">Tuesday/Thursday

<option value="3">Friday/Sunday

<option value="4">Saturday

</select>

<input type="submit" value="Send">

</form>

Page 3: PHP Programming What we know so far… …and something new.

processing forms…<?php// get form selection$day = $_GET['day']; // retrieve from form// check value and select appropriate itemif ($day == 1) { $special = 'Chicken in oyster sauce'; }elseif ($day == 2) { $special = 'French onion soup'; }elseif ($day == 3) { $special = 'Pork chops with mashed potatoes and green salad'; }else { $special = 'Fish and chips';}?><h2>Today's special is:</h2><?php echo $special; ?> …

cooking.php

Page 4: PHP Programming What we know so far… …and something new.

Rewrite with switch<?php// get form selection$day = $_GET['day'];// check value and select appropriate itemswitch($day){case 1: $special = 'Chicken in oyster sauce'; break;case 2: $special = 'French onion soup'; break;case 3: $special = 'Pork chops with mashed potatoes and green salad'; break;default: $special = 'Fish and chips';}?>

Page 5: PHP Programming What we know so far… …and something new.

strings

• Displaying and concatenating:

echo 'Items ordered: '.$totalqty.'<br />';

Page 6: PHP Programming What we know so far… …and something new.

logic• Relational operators: ==, !=, >, >=, <, <=

if ($age >= 21) {     echo 'Come on in, we have alcohol and music awaiting you!';     } else {     echo "You're too young for this club, come back when you're a little older"; }

• Conditional operators: &&, ||, !, xor

if (($year % 4 == 0) && ($year % 100 != 0)) || ($year % 400 == 0)echo $year.’ is a leap year</br>’

else echo $year.’ is not a leap year</br>’

Page 7: PHP Programming What we know so far… …and something new.

Tricky logic • A self-testing form<?php/* if the "submit" variable does not exist, the form has not been submitted - display initial page */if (!isset($_POST['submit'])) {?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Enter your age: <input name="age" size="2"> <input type="submit" name="submit" value="Go"> </form><?php }else {/* if the "submit" variable exists, the form has been submitted - look for and process form data */ // display result $age = $_POST['age']; if ($age >= 21) { echo 'Come on in, we have alcohol and music awaiting you!'; } else { echo "You're too young for this club, come back when you're a little older"; }}?>

Page 8: PHP Programming What we know so far… …and something new.

Increments/decrements/shorthand

notation• $total++ same as $total = $total + 1

• $total-- same as $total = $total - 1

• $line .= ‘more’ same as $line = $line.’more’

• $x += 5 same as $x = $x + 5• $answer = ($x == 10) same as:

if ($x == 10)

$answer = true;

Page 9: PHP Programming What we know so far… …and something new.

iteration

while (condition is true) { do this

}

do { do this

} while (condition is true);

for (startval of counter; condition; update counter) {do this

}

Page 10: PHP Programming What we know so far… …and something new.

Drawing tables<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">Enter number of rows <input name="rows" type="text" size="4"> and columns <input

name="columns" type="text" size="4"> <input type="submit" name="submit" value="Draw Table">

</form><?phpif (isset($_POST['submit'])) { echo "<table width = 90% border = '1' cellspacing = '5' cellpadding = '0'>";

// set variables from form input$rows = $_POST['rows'];

$columns = $_POST['columns']; // loop to create rows for ($r = 1; $r <= $rows; $r++) { echo "<tr>"; // loop to create columns for ($c = 1; $c <= $columns;$c++) { echo "<td>&nbsp;</td>"; } echo "</tr>"; } echo "</table>";}?>

tables.php

Page 11: PHP Programming What we know so far… …and something new.

File processing• File management activities:

– Creating– Opening– Writing data to a file– Reading data from a file– Locking– Deleting– Closing– Misc.

Page 12: PHP Programming What we know so far… …and something new.

Omelette recipe• Open the file and assign it a file handle.• Interact with the file, via its handle, and extract its contents into a

PHP variable.• Close the file.

<?php // set file to read$file = 'recipes/omelette.txt' or die('Could not open file!'); // open file $fh = fopen($file, 'r') or die('Could not open file!'); // read file contents $data = fread($fh, filesize($file)) or die('Could not read file!'); // close file fclose($fh); // print file contents echo $data; ?>

Page 13: PHP Programming What we know so far… …and something new.

Writing to a file

<?php // set file to write$file = 'tmp/dump.txt'; // open file $fh = fopen($file, 'w') or die('Could not open file!'); // write to file fwrite($fh, "Look, Ma, I wrote a file! ") or die('Could not

write to file'); // close file fclose($fh); ?>

Page 14: PHP Programming What we know so far… …and something new.

File existence<?php // if form has not yet been submitted // display input box if (!isset($_POST['file'])) { ?> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> Enter file path <input type="text" name="file"> </form> <?php } // else process form input else { // check if file exists // display appropriate message if (file_exists($_POST['file'])) { echo 'File exists!'; } else { echo 'File does not exist!'; } } ?>

Page 15: PHP Programming What we know so far… …and something new.

Multiple file functions• is_dir() - returns a Boolean indicating whether the specified path is a

directory• is_file() - returns a Boolean indicating whether the specified file is a regular

file• is_link() - returns a Boolean indicating whether the specified file is a

symbolic link• is_executable() - returns a Boolean indicating whether the specified file is

executable• is_readable()- returns a Boolean indicating whether the specified file is

readable• is_writable()- returns a Boolean indicating whether the specified file is

writable• filesize() - gets size of file• filemtime() - gets last modification time of file• filamtime() - gets last access time of file• fileowner() - gets file owner• filegroup() - gets file group• fileperms() - gets file permissions• filetype() - gets file type

Page 16: PHP Programming What we know so far… …and something new.

Other file functions

• pp. 71-76: special uses; will learn on a “need to know” basis– feof: end of file

– fgets, fgetss, fgetcsv: read a line at a time

– readfile, fpassthru: read whole file

– fgetc: read a character at a time

– unlink: delete a file

– rewind, fseek, ftell: inside the file– flock: locking the file

Page 17: PHP Programming What we know so far… …and something new.

arrays

• Composite, or aggregate, data types– Can hold more than one value using the same

variable name

• Examples– Quarterly earnings

– $q_earnings = array(3, 6, 1, 4);

3 6 1 4

[0] [1] [2] [3]

Page 18: PHP Programming What we know so far… …and something new.

arrays• Elements• Subscripts or indices• How to declare/define• How to manipulate elements

– Inserting– Reading– Deleting– Displaying– Processing

• Associative arrays

Page 19: PHP Programming What we know so far… …and something new.

Defining an array

<?php// define an array$pasta = array('spaghetti', 'penne', 'macaroni');?>

-or-<?php// define an array$pasta[0] = 'spaghetti';$pasta[1] = 'penne';$pasta[2] = 'macaroni';?>

Page 20: PHP Programming What we know so far… …and something new.

Defining an associative array<?php

// define an array

$menu['breakfast'] = 'bacon and eggs';

$menu['lunch'] = 'roast beef';

$menu['dinner'] = 'lasagna';

?>

-or-

<?php

// define an array

$menu = array(‘breakfast’ => 'bacon and eggs‘, 'lunch' => 'roast beef‘, 'dinner' => 'lasagna‘);

?>

Page 21: PHP Programming What we know so far… …and something new.

Adding/changing elements

• Adding– $pasta[4] = ‘rigatoni’;

or– array_push($pasta, ‘rigatoni’);– $menu[‘snack’] = ‘fruit’;

• Modifying– Just reassign the element

Page 22: PHP Programming What we know so far… …and something new.

Removing elements

• Removing from the end<?php

// define an array

$pasta = array('spaghetti', 'penne', 'macaroni');

print_r($pasta);

echo ‘<br>’;

// remove an element from the end

array_pop($pasta);

print_r($pasta);

?>

pastaarray.php

Page 23: PHP Programming What we know so far… …and something new.

Removing elements

• Removing from the front<?php

// define an array

$pasta = array('spaghetti', 'penne', 'macaroni');

// take an element off the top

array_shift($pasta);

print_r($pasta);

?>

Page 24: PHP Programming What we know so far… …and something new.

Adding elements to front

<?php

// define an array

$pasta = array('spaghetti', 'penne', 'macaroni');

// add an element to the beginning

array_unshift($pasta, 'tagliatelle');

print_r($pasta);

?>

Page 25: PHP Programming What we know so far… …and something new.

Strings arrays

<?php

// define CSV string

$str = 'red, blue, green, yellow';

// split into individual words

$colors = explode(', ', $str);

print_r($colors);

?>

Page 26: PHP Programming What we know so far… …and something new.

arrays strings

<?php

// define array

$colors = array ('red', 'blue', 'green', 'yellow');

// join into single string with 'and'

// returns 'red and blue and green and yellow'

$str = implode(' and ', $colors);

print $str;

?>

Page 27: PHP Programming What we know so far… …and something new.

Review functions

• array_push

• array_pop

• array_shift

• array_unshift

• explode

• Implode

• Also, sort and rsort!

Page 28: PHP Programming What we know so far… …and something new.

Looping through arraysMy favourite bands are:<ul><?php// define array$artists = array('Metallica', 'Evanescence', 'Linkin Park',

'Guns n Roses');// loop over it and print array elementsfor ($x = 0; $x < sizeof($artists); $x++) {    echo '<li>'.$artists[$x];}?></ul>

Page 29: PHP Programming What we know so far… …and something new.

A niftier wayMy favourite bands are:<ul><?php// define array$artists = array('Metallica', 'Evanescence', 'Linkin Park', 'Guns n

Roses');// loop over it// print array elementsforeach ($artists as $a) {    echo '<li>'.$a;}?></ul>

Page 30: PHP Programming What we know so far… …and something new.

Reading files into arrays• <?php

// set file to read$file = 'recipes/omelette.txt' or die('Could not open file!'); // read file into array $data = file($file) or die('Could not read file!'); // loop through array and print each line foreach ($data as $line) {      echo $line; } ?>

• <?php

// set file to read$file = 'recipes/omelette.txt' or die('Could not open file!'); // read file into string $data = file_get_contents($file) or die('Could not read file!'); // print contents echo $data; ?>


Recommended