Watkins Web 3: Blog

Posts tagged with “php”

Exercise 13: Reading/Writing to files with PHP

This exercise continues to use the weather report code but has you explore (a) more use of dynamic classes, (b) reading inputs from a text file, and (c) writing a history of inputs back into a text file.

Exercise 13 Exercise 13 Solution View Solution

Exercise 12: Weather

Using inline CSS in conjunction with PHP.

Exercise 12 View Demo

And here’s a quick reminder of the two types of inline CSS:

Page-specific CSS

You can wrap regular CSS statements in the <head> of your HTML page using the <style> tag:


<!doctype html>
<head>
<title>My Page</title>
<style>
     h1 {color:red;}
     p {font-size:24px; line-height:30px;}
</style>
</head>
...

Inline CSS on particular HTML elements

You can also style a particular element with the style attribute. This will override styles inherited from the main stylesheet or the <style> tag in the page.

...
<p style="font-size:24px; line-height:30px;">My paragraph is large.</p>
...

So if I wanted to generate a random font size with PHP and just affect a single paragraph, I could do this:

<?php
$font_size = rand(10, 50); // generate a random number between 10 and 50
?>
<p style="font-size:<?php echo $font_size; ?>px; line-height:30px;">My paragraph is large.</p>
...

Example of explode()

There are two things to remember here:

  1. The explode() function returns an array, where each element is a “piece” from the explosion. None of those elements will contain the explosion string itself. So if I explode on the colon character by writing explode(":", "here:are:four:words");, that will return an array of the four words themselves without any colons.
  2. If you want a particular element of an array, just access it using something like this: $the_third_element_of_array_name = $array_name[2]. The bracket syntax refers to a particular element in the array, so when you store it in a variable, it’s stored as a plain ol’ scalar variable, not an array.
// store a plain old sentence in $sentence
$sentence = "First half of the sentence, second half of the sentence.";
// explode $sentence into pieces wherever a comma appears, and store the (two) pieces that result as an array called $exploded_sentence
$exploded_sentence = explode(", " , $sentence);
// I just want the second piece of the explosion, so I'll access the second element of the array using $exploded_sentence[1] (remember, the first piece can be accessed with $exploded_sentence[0])
$second_half = $exploded_sentence[1];
// $second_half is a plain ol' scalar variable (not an array), so we can run IT through explode(). Let's do so by exploding on the space character: this will return as many pieces as there are words in the sentence
$second_half_exploded = explode(" ", $second_half);
// $second_half_exploded is of course an array, so if we want the first word, we just access it at $second_half_exploded[0]
$first_word_second_half = $second_half_exploded[0];
echo $first_word_second_half;

Exercise 11: Retrieving XML

Enjoy the magic of RSS, XML, and forms.

Exercise 11 Exercise 11 Solution View Solution

Exercise 10: Slicing and Dicing

Exercise 10 Exercise 10 Solution View Solution

Exercise 9: Looping and Data Retrieval

This exercise should be run on your web host. Make a new folder called ex9 somewhere in your account and upload all the files you’ve edited each time you need to see a change.

Exercise 9 Exercise 9 Solution View Solution

Cheat Sheet: Review of PHP Fundamentals

Variables

$string = "Tennessee";
$age = 24;
$double_age = 2 * $age;
$age_plus_ten = $age + 10;

Arrays

// numeric array (AKA indexed array)
	$items[0] = "orange";
	$items[1] = "apple";
	$items[2] = "pear";
	echo $items[1]; 		// outputs apple
	// associative array
	$items[username] = "Joe";
	$items[school] = "Watkins";

Conditions (Control Structures)

if ( $age > 20 ) { 
		echo "you are older than 20"; 
		echo " and that is great."; 
		}
	else {
			echo "you are younger than 20"; 
	}

Functions

// built-in to PHP
	$the_year_now = date('Y'); // stores 2012 in my variable
	// build your own
	function year_plus_one() {
		$output = 1 + date('Y');
		return $output; 
		}
	$the_year_plus_one = year_plus_one(); 
	$the_year_plus_two = $the_year_plus_one + 1;
	echo $the_year_plus_two; // outputs 2014

Loops

// FOR loop
		for ($i = 1; $i <=10; $i++) {	
			echo ("the counter is at $i");
			}
	// FOREACH loop (only for arrays)
		$items[username] = "Joe";
		$items[school] = "Watkins";
	foreach ($items as $key => $value) {
			echo ("For this element, the key is $key and the value is $value.");
		}

PHP 5.4 released March 1st

PHP5.4 Banner
PHP 5.4 is here

Newly released PHP 5.4 is here with some new features. The most interesting one to me is the new CLI virtual server. Some other interesting features include: Default character set changed from ISO-8859-1 to UTF-8, shorter array syntax and traits for classes.

Cheat Sheet: PHP Functions

Functions are a very powerful tool in PHP that help you follow the “DRY” rule of programming: Don’t Repeat Yourself. Functions essentially let you use and construct self-contained actions that can be executed multiple times throughout your page or your website. Think of a function as a little factory: you give some input, and the function “returns” some output to you. As long as you know what the function does, you don’t need to worry about its particular internal mechanics — and you won’t see the process — each time you run it.

Here are three things to remember about functions:

  1. Functions can output information into your document (if they use an echo or print statement), but more often they just return information. “Returning” the info allows it to be stored in a variable of your choosing, but it does NOT echo it. It’s mainly an issue of control: when a function returns a value, you can store itin a variable and manipulate it further before you decide to echo it.
  2. Some functions require one or more inputs (aka “parameters” or “arguments”) to work, and behave differently depending on what you input. Other functions don’t need any input. Still others make the input optional and use a default value if you don’t specify one.
  3. Some functions are native to the PHP processor, but you can also define your own. To do so, use the word function, your function name (with parentheses), and then curly braces specifying what should happen with whatever inputs are provided. See “Defining your Own Functions” below for an example.

Running Functions

PHP functions can be recognized by the syntax function_name() or function_name ("some input"); the parentheses are the place we insert our parameters, if any. The date() function, built-into PHP, uses the server clock to look up the current date and return whatever it is to the PHP process. date() accepts a letter of the alphabet so that you can choose what part of the current date — and in what format — you want the function to return a value. (It’s hard to remember which letter input retreives which output — most people just look up the answer on this PHP.net reference page).

A small number of functions can be run without storing their returned output. The classic example is echo, which takes as its input whatever string you want to appear in the web page:

<?php
	$my_message = "Hello World"
	echo ($my_message); // outputs "Hello World" on the web page.
?>

Another example is date_default_timezone_set, which takes a location string as its argument and alters the time zone setting for subsequent PHP code:

bc(brush: php). date_default_timezone_set(‘America/Chicago’); // doesn’t echo anything, but any date or time function run after this will be according Central Time
?>

But more common are functions designed to have their returned values stored in variables that we create:

<?php
	$this_month_ = date('F'); // stores something like "February" in $this_month
	$this_year = date('Y'); // stores something like "2012" in $this_year 
?>

Some functions take multiple variables as their arguments. In these cases, you need to be sure to input them in the correct order. Let’s use the substr function (“sub-string”), which needs to know both what the string is and how much of it you want in order to return a sub-string. When you look up the instructions, you’ll see you can specify (1) the string, (2) the position of the first character you want, and (3) how many characters to include from that point.

<?php
	$string = "apples";
	$segment1 = substr($string, 1, 3);  // returns and stores "ppl"
	$segment2 = substr($string, 0, 5);  // returns and stores "apple"
?>

Defining Your Own Functions

Functions are possibly easier to understand when you define your own, rather than using one of PHP built-in functions. Here are some things to keep in mind:

  1. You only need to define your function once, and it doesn’t matter where in your web page you do so: code written before or after the function definition can “call” that function and it will work. The function does need to be defined on the same page on which it is called, but you can use a PHP include: you will often see an something like include ('site-functions.php') at the top or bottom of a page, and the site-functions.php file will be used to store every function that the site might need.
  2. Functions that take parameters/arguments need to be written like math formulas, where those parameters are variables: in other words, you need to abstract as much of the logic so that the function can be given different values and always return a different result that is correct for those inputs. See the example below:
<?php
	// define the average_these_numbers function, which requires two arguments
	function average_these_numbers($number1, $number2) {
		$sum = $number1 + $number2;
		$average = $sum/2;
		return $average;
	}
?>

The code above creates and defines how the function will work (note the reserved word function at the beginning), so it only needs to be done once. Once defined, that function can be run repeatedly on different number pairs:

<?php
	$avg = average_these_numbers(4, 8);  // returns and stores 6
	$avg = average_these_numbers(10, 20); // returns and stores 15
	$first_number = 4;
	$second_number = 16;
	$avg = average_these_numbers($first_number, $second_number); // returns and stores 10
?>

Note that in the last example, the inputs were first stored in scalar variables and then passed as inputs to the function. And notice that we did not have to use $number1 and $number2 as our variable names. Yes, we happened to use $number1 and $number2 within the function definition, but once defined, we can run the function by passing any two values to it, and the function will always treat the first input as $number1 and the second input as $number2. The fact that we passed in our parameters using $first_number and second_number when running the function is no problem.

Hopefully this makes some intuitive sense — it has to do with the “scope” of the variables we are using at each stage. You can read more about variable scope on the PHP.net site.

Exercise 7 (Blog Loop and Stylesheet)

This exercise requires you to loop through some provided blog posts and write a quick stylesheet to lay the content out on the page. As usual, you’ll need to create a new directory on your server space and upload your files there each time you make a change.

Exercise 7

Cheat Sheet: PHP Loops

Loops are probably the final fundamental programming concept we’ve covered. Here’s a quick review of the syntax for the three primary varieties:

While Loops

while loops execute the code inside the curly braces repeatedly, and don’t stop until the “while condition” stops being true. The typical trick is to use a $counter variable that increments each time the loop is run. (The loop remembers variable values from the previous iteration of the loop, so eventually the while condition will stop being true and the loop will stop running.)

<?php
	$counter = 1;  	 
	while ( $counter <= 6 ) { 
		echo ("<p>Now the counter is at $counter.</p>");
		$counter = $counter + 1 ; 
		}
?>

This will produce the following HTML:


	<p>Now the counter is at 1.</p>
	<p>Now the counter is at 2.</p>
	<p>Now the counter is at 3.</p>
	<p>Now the counter is at 4.</p>
	<p>Now the counter is at 5.</p>
	<p>Now the counter is at 6.</p>

For Loops

for loops are similar to while loops but have slightly more elaborate setups. Rather than create and increment the $counter variable inside the loop alongside the code to be repeated, it all gets set up at the beginning. The setup is strict: you have to specify the starting value of the $counter variable, then the “while” condition, then the incrementing statement, all separated by semicolons.

<?php
	for ($counter = 0; $counter <= 6;  $counter = $counter + 1) { 
	echo ("<p>Now the counter is at $counter.</p>");
	}
?>

(This code produces the same HTML as the while loop above.)

Foreach Loops

A foreach loop is exclusively for looping through the elements of an array. As usual, an example explains this best:

foreach for Indexed Arrays

Very often we have an indexed array and want to output the values of each element. We can’t simply run echo($array_name) — that will throw an error because we haven’t specified which element we want echoed. If we want to echo each element in turn, we run a loop:

<?php
	// create indexed array of users
	$users[0] = "joe";
	$users[1] = "jane";
	$users[2] = "jill";
	$users[3] = "jeff";
	// loop through each element
	foreach $users as $each_user { // notice we create a temporary scalar variable ($each_user) for the purposes of accessing each element value in the foreach loop
		echo ("<p>A user is named $each_user.</p>");
		} 	

which will produce the following HTML:

<p>A user is named joe.</p>
<p>A user is named jane.</p>
<p>A user is named jill.</p>
<p>A user is named jeff.</p>

foreach for Associative Arrays

Associative arrays get a little more complicated, because you may want to access both the key and the value of each element within the loop. Note the $key=>$value syntax.

<?php
	// create associative array of user joe
	$user[name] = "Joseph Schmoe";
	$user[age] = 25;
	$user[nickname] = "Joe";
	$user[catname] = "Esmerelda";
	// run the loop
	foreach ($user as $key=>$value) {
		echo ("<p>This array has a key $key with a corresponding value $value</p>");
		} 	
?>

… which will produce the following HTML:

<p>This array has a key name with a corresponding value Joseph Schmoe</p>
<p>This array has a key age with a corresponding value 25</p>
<p>This array has a key nickname with a corresponding value Joe</p>
<p>This array has a key catname with a corresponding value Esmerelda</p>

Cheat Sheet: PHP Variables and Arrays

First, let’s go over three basic requirements for PHP code to be executed:

  1. Your filenames must end in .php to be interpreted as PHP by the server.
  2. All PHP code must be written inside opening (<?php ) and closing (?>) PHP tags
  3. Your files must be hosted on a server that runs software (usually Apache) that runs PHP files.

Upshot: if your browser is spitting out raw PHP code instead of executing that code, check the three above requirements.

Scalar Variables

In PHP, variables begin with a dollar sign ($) and can be used to store pieces of text (aka strings) as well as numbers. We store information in variables with a PHP statement that begins with the variable name and is followed by the equals sign (aka the “assignment operator”) and the value we wish to store. Note that strings need quotation marks around them, while numbers do not. Variable names cannot contain spaces, hyphens, or most punctuation characters besides the underscore (_). They also may not begin with a number.

<?php
	$my_name = "Joe Schmoe"; // a string needs quotation marks
	$my_age = 23;			// a number doesn't need quotation marks
	echo ("<p>My name is $my_name and my age is $my_age.</p>"); 
?>

When a browser requests our page, PHP will echo the string as HTML (the text in quotes above) but replace the variables with the values that have been stored i them:

<p>My name is Joe Schmoe and my age is 23.</p>

As we’ve explored in class, there are a variety of ways to combine, manipulate, and change variables. Remember that PHP is procedural and in many cases the sequence of your code matters:

<?php
	$my_name = "Joe"; // $my_name is now assigned the value "Joe"
	$my_name = "Fred"; // $my_name is now assigned the value "Fred" -- "Joe" is erased from memory
	$my_name = $my_name . " Shropshire"; // use concatenation operator (.) with a string to assign $my_name the value "Fred Shropshire".
 	$my_age = (5 * 30) - 100; // $my_age is now 50
?>

Arrays

Arrays are also a kind of variable, but they are a bit more complex than scalar variables. If you think of a scalar variable as a text file, arrays are a spreadsheet: they store multiple “elements” in a sequence, and you can access particular elements separately.

Associative Arrays

Suppose you have some information about a user. Rather than store that information in m variables ($user_name, $user_age, $user_nickname), you could use an array to store all that information in the variable $user. Arrays have the following structure: each “element” (an item in the array) has both a key and a value. The key is essentially a name for the element: it identifies which one we’re dealing with, while the value is the contents of that element. For example:

<?php
    // create array elements and assign values
	$user[name] =  "Joseph Schmoe"; // element 1: key is the string "name", value is the string "Joseph Schmoe"
	$user[age] =  25;               // element 2: key is the string "age", value is the number 25
	$user[nickname] =  "Joe";       // element 3: key is the string "nickname", value is the string "Joe"
?>

You access and output the value of each element with the same syntax:

<?php
	echo ("<p>The user is named $user[name], is $user[age] years old, and is nicknamed $user[nickname].</p>"); 
?>

Indexed Arrays

An indexed array is simply an array where the keys are numbers, starting with 0 and incrementing by one whenever an element is added. Indexed arrays are easier to manipulate programmatically (the array keys are fairly predictable), but of course the keys don’t carry much information about what value is stored in each element. They’re most often used for lists of content where the meaning of each element is obvious from the variable name:

<?php
	    // create array elements and assign values
		$site_users[0] =  "jschmoe";
		$site_users[1] =  "bsmith";
		$site_users[2] =  "ajones";
		$site_users[3] =  "cwilson";
?>

If you leave out the keys when assigning the value to an element, PHP will just create numeric keys for you, incrementing them as it goes. So this does exactly the same thing as the code above:

<?php
	    // create array elements and assign values
		$site_users[] =  "jschmoe"; // automatically gets array key 0
		$site_users[] =  "bsmith";  // automatically gets array key 1
		$site_users[] =  "ajones";  // automatically gets array key 2
		$site_users[] =  "cwilson"; // automatically gets array key 3
?>

Using Arrays

We’ve already seen how PHP will replace any variable with its value. What’s tricky about arrays is that you can do this with the keys as well as the whole element:

<?php
		$attribute = "nickname";
		$user = "3";
		echo $user[nickname];      // outputs "Joe";
		echo $user[$attribute];    // also outputs "Joe", because $attribute = "nickname"
	    echo $site_users[3] ;      // outputs "ajones"
	    echo $site_users[$user] ;  // also outputs "ajones", because $user = 3
?>

Exercise 6: PHP Functions, Loops

Exercise 6 Exercise 6 Solution View Solution

Exercise 5: PHP Variables, Arrays, Includes, and Control Structures

The demos and exercises for this exercise are written as PHP comments in the files themselves. Start with index.php and then move on to index2.php, modifying the files and creating new ones as needed. Since PHP requires Apache to execute the code, you’ll need to upload them to your server space.

  1. Download the zip file below to your desktop and unzip it
  2. Use Cyberduck to connect to your watkinswebdev.com server space; create a new folder called exercise5
  3. Upload the contents of the local ex5 folder into your remote exercise5 folder on your server space. You should now be able to view index.php by visiting http://watkinswebdev.com/[username]/exercise5/ (remember, URLS that end in a slash (/) refer to directories, and index.php always gets loaded by default if it exists
  4. Open the four text files in the ex5 folder on your local machine in Textwrangler. Now read and follow the instructions in index.php while viewing the output at http://watkinswebdev.com/[username]/exercise5/. When you need to change the file, edit in Textwrangler, save it, and upload it to your server space, overwriting the old version. Hit refresh in your browser to view the results.

Note: for PHP exercises, “View Solution” will of course only show the rendered HTML output. Download the source files to see the PHP that makes it happen.

Exercise 5 Exercise 5 Solution View Solution