Now that I have your attention, let's try a different method here from our shared lecture of last week. A more intimate one-on-one between you and some text - interrupted often by reinforcing activities. The text is mostly mine (yet influenced by personal experience and what I've read on the Web - something you can do as much of as you want to as well). The goal is to motivate you and let you get a sense of where you are at with this thing called PHP. Some of you will be able to fly through this. Others will need to spend as much time as you can muster between now and September 22nd (6:30pm sharp) - our next time in class together. For those who whiz through it, be happy you didn't have to sit through three hours worth of lecture to get there - and spend the time gained doing something fruitful with PHP learning - read, do, explore, and motivate yourself on our projects. For those who stagger through it at a snail's pace, be happy you aren't out of breath trying to keep up in a rushed lecture and know you are getting your money's worth (especially if you reflect on it often). You too can read, do, explore, and motivate yourself on our projects. That's first and foremost for this week: read, do, explore, and motivate yourself on our projects (need I write that once again?).
Your First PHP Page
I have generated starter pages for you for all four of our projects. The files sit within the /var/www/html/dynphp/bdc folder of our www.oworld.org host server. We all tried logging into the server during class on September 8th. You will need the login userid and password to perform the following steps. If you did not write those down, please contact a class member to get them verbally (don't transmit our id and password via e-mail). Follow these steps to set up PHP starter pages in your own server folder:
Login to the server
Use your favorate SFTP-capable software to drag and drop files on our server (or if you know 'ssh2' commands via a terminal window, by all means uses those to type commands to sftp files to your folder on-line). I recommend Fetch on the Mac (since we have it in our classroom) and SSH Secure Shell on Windows machines (XP, Vista, etc.). I use Cyberduck which is a great tool for your own Mac (I use SSH Secure Shell on my XP machine and in conjunction with Parallel Tools on my Mac OS X MacBook). Open up your SFTP tool and type in our host name like this:
Type in the Username and Password and connect to the server. Use the 'Go' or 'Go to Folder' menu item on the menu bar to go to our folders within the Web root. Your tool should work something like this:
Your tool should now show you all the folders that are in our course Web root. Hopefully, you recognize your folder here:
The bdc folder is my folder which will show you examples of our projects from time to time. Open the bdc folder. You'll see three subfolders there for now: artstar, cev, and opod which have very rough starter pages in them for projects 1, 2, and 3. Go ahead and open the artstar folder. You should see three files there:
These files are named according to a very popular convention. The default page in a PHP-enabled Web directory is often named index.php because the server knows to automatically associated that file with the URL to the directory in which it exists. For example, if you look at http://www.oworld.org/dynphp/bdc/artstar/ in your favorite Web browser, you will notice that the index.php files is served to your browser - after being processed by the PHP dynamic content engine that runs on our class server.
The header.php file contains header HTML or XHTML code that we wish to include on more than one page within the site - the name is used quite conventionally. Ditto for using the name footer.php for content that will appear at the bottom of more than one page on your website.
Investigating PHP Code
To investigate these three project 1 starter files, you need to drag-and-drop them from the server onto your hard drive (anywhere is fine, but why not the desktop for now?). Then, open those pages in any text editor you wish to use to look at them with. I show you the files opened in Dreamweaver below only because Dreamweaver CS3 is available in our classroom. And, because the color-coding feature of the Dreamweaver code view will assist me in writing about the content of the files.
Drag the three files onto your hard drive. Drag them onto a text editor icon (like TextEdit on the Mac or Notepad on a Windows-based machine) or use your favorite HTML editor if you prefer. header.php contains a bunch of HTML code that creates the common top banner on all pages within the artstar.org webroot directory. Note all the absolute URLs I put into that page so that links and images within the banner work as they would on the ArtStar site. We will want to use relative links within your content, but you can keep any absolute URLs anytime you are merging code to existing Web content in this class. Also note there are no PHP directives within the header or footer files! You don't have to use PHP to use the .php extension within a filename on a server that process PHP. The header and footer typically use the .php extension even if they don't need any PHP processing on their contents.
Let's take a look at the code behind the index.php file:
The PHP directives identify where the PHP dynamic content engine should process our code. A PHP directive starts with a less-than symbol question mark sequence and continues until a question mark greater-than symbol sequence is found. So, the first line:
<?php include("header.php") ?>
tells the PHP processor to wake up and do something on behalf of our intended Web content. The processor recognizes the php include("header.php") request as a request to place content from a relative URL up on top of the content that exists within the file in which it is contained (the index.php file in this case). The footer directive is similar in that is also uses an include() call to grab content from an external file. By seeing just these two cases, you should surmise correctly that you can place an include anywhere in a PHP page and it will be inserted within the flow of the document where it is found. There are many pages on the Web that are just a series of include() directives to other content on the Web. Sadly, you can't tell that is the case by looking at content within your browser because the processing has happened at the server before the final page content was sent along the communications link to your browser (or user agent should you be listening to spoken content in your car or using a Braille system to experience it as a series of bumps under your fingers - browser really ins't the most politically correct word, but it sure is conventional, eh?).
When PHP parses a file, it looks for opening and closing tags, which tell PHP to start and stop interpreting the code between them. Parsing in this manner allows php to be embedded in all sorts of different documents, as everything outside of a pair of opening and closing tags is ignored by the PHP parser. Most of the time you will see php embedded in HTML documents, as in our ArtStar example above. One of the most popular PHP commands is the echo command:
which just echos back the text contained within single-quotes or double-quotes to the technology that is being served (in our class, this will be mostly HTML, XHTML, or CSS code). Every PHP statement can end in a semi-colon to distinguish from other statements (and give you the freedom to place more than one command on a line). This echo statement (statement is the generic term for something you send a process (like our PHP engine) while command is a more specific term telling the process to do something on our behalf - commands are a subset of statements but we'll use the words pretty much interchangably). Above, we are echoing Mary Ellis' name to our Web page that returns from the dynamic PHP process, modifying the font to be more specific in how we want it to appear.
Give it a Test Ride
Go ahead and copy the three artstar files from my bdc folder to your desktop and then up to your folder within the server's webroot so you can begin to experiment with PHP code (and continue to practice your HTML, XHTML, and CSS skills). If you put files on the server in a place that is not within the webroot or its subdirectories, they will not be processed by the PHP engine nor served via our HTTP services (managed by Apache on our server). This is why I also gave you a folder within our server's /home/ directory as a place for you to back-up files without them being indexed by any Web indexing program (the so-called spiders that Google, Lycos, Microsoft, etc. uses to index the Web and use in search engine queries). You can play by following these steps iteratively:
Use your favorite text or content editor to create or edit a .php file on your local computer.
Save your changes and upload your file to your directory within our /var/www/html/dynphp directory on the class server (remembering or referring back to the steps shown above to do so).
When the upload is complete, go to your Web browswer and refresh (reload) the page so you can see your changes. Remember that the http://www.oworld.org/ domain name is the webroot for our server. So, your directory is accesssible via http://www.oworld.org/dynphp/xxx/ (where your initials appear in the 'xxx' directory).
For me, I see the page whose PHP code is shown above at:
You should do this iteratively as often as you need this week to feel comfortable with the process as we'll be doing this for all four of our projects as well as to do examples together in class (you don't have to follow along in class if you are a note taker, but is problematic if you don't feel comfortable doing things we do in class). If you are struggling with this, please send me a e-mail message or bounce me a CE Link message via our participant roster on our CE Link RISD site. I can call you from Milwaukee at an agreed upon time to walk through it together.
How a PHP Cache Works
When you write new PHP statements and upload a file to the server, you will notice a wide range of performance in how fast your page reloads in your browser. The delay is not likely at your end unless you happen to be on a very slow Internet connection or there is a major outage or runaway process on the Web somewhere. Instead, the delay is within the PHP process itself. Requests for PHP processing can pile up when multiple people are using the same single server. But, the PHP engine has a trick available to administrators like myself. Popular PHP queries can be run and saved in the cache such that they can be served immediately without having to be recomputed.
Think about that within the context of our class goals. We want to be able to have highly dynamic pages which means our content can change via changes to our PHP statements or changes to the data we access in our database(s). A good PHP process cache must constantly check whether our PHP code has changed or if our data has changed. If either of these do change, the PHP engine must refresh the result being held in the cache. One huge benefit of using an Internet Service Provider who can afford a huge amount of live computer memory is that more PHP results can be held in the cache and maintained to be as fast as possible in serving those requests that request it on a regular basis. I am extremely impressed how Go Daddy's PHP and mysql caches work. I feel confortable writing very complicated database queries and convoluted PHP statements that work with that data - because I know the cache will update the page that gets returned and keep it in the cache upon the first running of the new statements and data changes. But, here's the trick: I always run the code myself first myself in a browser so it is in the cache before anyone else has to wait! This sounds obvious since you'll want to verify your results anyway, but some people (like myself) cut corners when it comes to code (when the world isn't going to end based on a mistake - and I don't work on that code in the first place). The cache has motivated me not to cut corners as some of my queries take upwards of five minutes to run on even Go Daddy's quick databases.
In our class, you can likely forget about the cache. For one reason, the cache is very small on our very humble server from 1997 technology (hey - if your code performs on there you can have confidence it will work almost everywhere - there is benefit to using old technology during develoment). And, for another reason, our PHP statements and databases are not likely to get so complex (which is why I need to make you aware of this cache issue early and often for any professional work you do). OK, enough said. Let's start learning some PHP (and let's make the commitment to never stopping to do so - as long as we want to be effective layout and information designers).
Basic PHP Syntax
I learn PHP best by following discussions among programmers who write PHP code often. I like dialog in my novels to break up all that description that some writers go overboard on (I am more a plot guy outside of one deep description of the character I am supposed to be taking over for the ride in the story). Many PHP support groups (PHP Anonymous, anyone?) follow an on-line recipe of presenting an interesting description of something interesting that can be done wth PHP and then opening up a discussion on the implications, efficiency, and usefulness of that topic. Take a look at http://www.php.net/basic-syntax and read through the page while noticing how the format opens up a discussion with anyone on the Internet (or at least those invited guests who have been selected for their brilliant track record).
Thousands of Informative Pages
There are literally thousands of such code-suggestive pages on the Web for any popular computing language. It behooves you to get used to thinking in bite-sized chunks because this wonderfully collective reference is there for the taking. I love sitting under a tree somewhere and reading a book sequentially. In fact, my ideal vacation is on a beach with a good popular science book which I read cover to cover. But, it is not the ideal way to learn a computing language like PHP. I believe in the power of our redundant senses and in how redundant information from different senses builds our associative memory in ways that make us smarter (Jeff Hawkins' On Intelligence book resonates well with me on this topic because it rings so true in how my own smarts have been improved over time). Get your eyes and your fingers involved in the learning process. Read something and try it out! Read something more and try it out! Stop occasionally to reflect on everything you've been doing. And, then most importantly, get away from it and do something active that takes the burden off your consciousness so your sub-conscious can do some housekeeping with your new information. My suggestion is to save the most important things you need to learn for intense multi-sensory learning just before you go to sleep (for the evening or that power nap). Then sleep on it. If your brain gets used to that pattern, it will do amazing things while you sleep - including invading your dreams at times with powerful insights that just need to be interpreted to real world ways.
So many of us have found this trick to be so consistently successful and efficient that all our dicussions follow that pattern (hence the popular referencing formats like this example above). And with the Web and on-line repositories, we get this amazing ability to improve our collective intelligence by taking advantage of time zones brought on by a rotating planet. My favorite coding projects are those with teams dispersed eight hours apart. For example, I worked on a project with a team in Tuscany, Italy and Melbourne, Australia while I was in Seattle working with Californians. Our day started by reading updates as to where our Tuscan team had gotten during their workday. They put their questions in writing and we answered them in the flow of our workday (while they slept!). Then we gave an update to our Aussie team and asked questions of them. They worked and answered our questions while we slept. I would get up in the morning, pour a nice strong cup of bitter coffee (as all us Seattlites seemed to do), and delight in quietly reading the answers to all my questions! They were all answered and discussed in a manner like this page above. We all became so thankful for each other and we took our eight hours off from the moment we woke to eight hours later doing things we loved knowing that working would not be very useful - the next team was handling it all for us.
So, you aren't convinced. There is that recommended text book to play with in this class. And, there are plenty of run-on sequential pages on-line to read for learning (like this lecture page is becoming). Just Google with the word 'tutorial' on the topic you are interested in reading sequentially on. Do some empirical tests though - try learning both ways (with or without doing while you read) and see if your hardfast behaviors are in fact more enjoyable and more fruitful for your personal goals. Then ask yourself who multinational companies are frantically trying to set up coding teams eight hours apart from each other (the insurance company I worked for chose Ireland, China, and the US for good reason, in my humble opinion (abreviated as IMHO from now on as you might see often in these technical resources that are open to discussion)).
The rest of this lecture points out important concepts to get you started. I recommend reading each tidbit and then trying to implement it in one of our projects from class. Get into the swing of interactivity and iteration and see where it takes you.
PHP Data Types
No topic will be more important than understanding PHP data types - only because we will be connecting to databases holding data that we will want to manipulate and present properly to our Web audience. Ask yourself, "did I spend the requisite time to really understand all the HTML data types I have used in writing Web pages?". If the answer is, "perhaps not but how would I know?" (because you like to answer a question with another question), then take a look at http://www.php-editors.com/html4ref/types.html. It might be a little too technical for your likes, but it does a good job of outlining the types of data HTML incorporates. And guess what... since PHP is just a way to identify dynamic content for a static language (like HTML), the data types contained in PHP will need to align with the end-result content in order to be of maximum use.
The Basic Building Blocks
To focus on variable and PHP data types, I repeat the tutorial from http://www.smartwebby.com/php/variable.asp, but with my edits, here:
Variables are nothing but identifiers to the memory location to store data (think of an identifier as a label - you are identified by all the labels people put on you, first and foremost your name). In PHP code, we can create hundredds of variables in a single .php document. In PHP all variables in your code must begin with a dollar sign "$" and the value can be assigned using the "=" operator as shown below:
Another important thing in PHP is that all the statements must end with a semicolon ";". In PHP we needn't specify the variable type (type referring to how data is formatted in dynamic memory or the stored memory of a hard drive), as it takes the data type of the assigned value (you assign something and PHP figures out its type from how you wrote what was being assigned to that label). In the above example, the PHP engine understands that '$Name' is of data type String and '$Age' is of type Numeric.
Limitations in Variable Naming:
PHP has no limit on the length of variable name as in the case of other programming languages. The variable name must start with a letter or underscore. The variable name must be a combination of letters, numbers and underscores. Other characters such as *, +, #, @ are not allowed and causes an error if used.
Data Types in PHP
In PHP the data type of a variable is not set by the programmer. PHP decides the data type of variables after interpreting the Web page. Data Types in PHP include:
Numeric data type
String data type
Array data type
Numeric data type
Numeric data type is used for a number. There are two different numeric data types:
Integer
Double
Integer Data Type
Integer data types contain whole number values.
Doubles
Double contains double-precision (usually 32 bits) floating point numbers.
String Data Type
String data type is used to contain textual information or sequences of letters combined with numeric digits. The value is assigned within quotes as shown below.
String Concatenation
String Concatenation is a process of adding two strings. This is done by attaching one string to the end of another string. This is done by using '.' (period) operator as shown below:
Array Data Type
Array data type is used to contain many values in a single variable. Each array element can be retrieved by using the array variable name and its key/index value. We can declare an array variable in different ways as shown below:
Example:
$arrMark[0] = 95;
$arrMark[1] = 88;
$arrMark[3] = 77;
(Or)
$arrMark = array(95,88,77);
In the above example, the variable 'arrMark' contains three different values. In the first method the array elements are stored using the key values (0, 1, 2), but in the second example the keyword 'array' is used to assign values to the array variable. By default, array key element starts with 0.
The array elements can be accessed by using their key values. The different marks stored in the array elements can be added together to obtain the total marks as shown below:
In the above two examples we have used the key values as numbers, but it not necessary that the key value must be a number, it can also be a string as shown below:
What are you waiting for?
That's a lot of powerful information - presented in a format that isn't very obvious to our brains unless we've studied a lot of other programming languages to train our brain previous. I recommend that you try out all these data types in the ArtStar gallery page for Mary Ellis. Make 'Mary Ellis' the value of a String variable you can reuse in echo statements:
and notice how the variable works to allow you to reuse the same exact PHP statement with different results (imagine tying that into a database, adding a loop to crunch through many artist names, and presenting a list of all artists in the ArtStar community from which a Web visitor can choose). Get to work trying out all the variable data types in the tutorial in as many creative ways you can imagine given your limited skills so far. Commit yourself to investigating whether this is the most effective way for you to learn and maintain motivation while doing so. Ask yourself, "hey... do I feel empowered and above intimidation?". I wish you that.
But, most of all: make some mistakes! Get used to saving your previously working version and butchering a new version with a wild attempt at something that might work. See what the browser does with it upon getting your result back from the PHP engine. Get used to the CNTL-Z keyboard chord to undue what you have done most recently. Get a rhythm until it feels hardwired in your brain. That's all intelligence is to me: the ability to do something from past experience (heavily emphasized by an associative memory). Birds are much more intelligent fliers than we are and yet look how small their brains are! We call can do this as well as we can tie our shoelaces. We just need to get the rhythm down. Now is the time to do that as we are going to go over a lot in this course and you like swimming downstream, frolicking in the water as you do so (seriously, I am suggesting a good five hours strong this week while you have the comfort of your own computer, your own favorite place, and your own speed at doing and learning - use our three hour time slot for this at least).
Mathematical Statements
Definition: Mathematical operators preform simple math calculations on the operands in an expression. Four basic (and universal) mathematical operators are multiplication (*), division (/), subtraction (-), and addition (+).
Examples: An example of addition:
$my_canvas_count + 4 = 10
An example of subtraction:
$my_canvas_count - $your_canvas_count = 3
An example of multiplication:
$your_canvas_count * 10 = 30
An example of division:
$my_canvas_count / 2 = 3
There are many mathematical operators that all work in the same fashion (are placed in the flow of a statement as a single character that suggests a mathematical operation to take place). You should be able to determine the values both $my_canvas_count and $your_canvas_count
contain before these operations took place. The answers would differ if the values were not fixed as they must have been. One of my favorite mathematical operators is the mod operator. In PHP (and many other languages), mod is represented by the '%' symbol. If you don't know what mod is, Google it! In a programming course like this, you must develop that reflex of searching for a term to understand it better. Or else, continue along half understanding something and seeing how far it will get you. I would do you a disservice by explaining every term sequentially (and boring those who already understand a term) or by giving you a link to it. I believe a huge part of becoming good and comfortable at languages like PHP is in gaining your own independence and swagger by repetitively proving to yourself you are self-sufficent and willing to fight through mistakes through a relentless iterative attempt at making examples work with the ideas you have in your head. What other mathematical operators can you find on the Web that are relevant to PHP? What operations can you perform using variables you create yourself using the rules exposed above? Try out as many combinations it takes for you to get your confidence up for next week's class together. Send me e-mail if you are patting yourself on your back. I'll send back a reassuring message from the road along with a sign of relief that you are succeeding.
That's all the lecture for this week. The rest is up to you. Dive into some good PHP tutorials on the Web if you have some time leftover:
And, spend some time meditating on your resolve and motivation and getting to understand how your brain works better so you can learn more effectively for yourself. Remember when your first grade teacher told you that math was important at that age for developing your brain to think for itself? Well, this process is important for all of us at any age so that we can all become better at participating in the emergent global consciousness that is being formed rapidly by this Web we are so amorous of (for better or worse, eh?). Ha! Can't end lecture with a preposition (what poor form). So, I'll say 'adieu' to finish here.