Dynamic Web Development
Fall, 2011
Christopher Sung
Interactive Telecommunications Program, NYU
Class 2 - PHP Basics & Web Page Scripting

Contents:


PHP Background   [top]
PHP started as a set of Perl scripts created by Rasmus Lerdorf in 1995, who named this set of scripts 'Personal Home Page Tools'. It was eventually implemented in C and given the same acronym but with a recursive meaning - PHP: Hypertext Preprocessor. Today, PHP is being used by an estimated hundreds of thousands of developers, with several million sites reported as having it installed, which accounts for over 20% of all domains on the Internet.


Getting Started   [top]
Our PHP scripts will live on the ITP Stage server (stu.itp.nyu.edu). A PHP script can be executed using the command-line while logged into the server, but for our purposes, they will primarily be executed by a web user over the Internet. All your PHP scripts should have a ".php" extension, i.e. "hello.php" or "my_pix.php" and can contain HTML, Javascript, and of course, PHP. In fact, a ".php" file can contain only HTML and still display fine, but if your file contains actual PHP code, then it must have a ".php" extension to execute properly.

Here's a few things to know about making PHP statements, comments, and formatting the code:

PHP is often interspersed with HTML and as such needs it's own set of delimiters to say which parts of the document are PHP blocks. This syntax is:

<?php
# This is a comment in PHP
print "What a stupid example!";
?>

Did you see the # in front of the comment? Did you also see the ; that ends the next line? This is because the first line is a comment, and the 2nd line is an actual statement. When you use the print command, you're sending that text straight to the browser over the web.


PHP Variables   [top]
PHP has several different data types. The most common are scalars which hold a single value, and arrays which can hold multiple values. The character of the realm with variables is $ (dollar sign). It signifies a variable that can hold a single value or a set of values, and these values can be numbers or strings, or even references to other variables. Here some common uses of variables as scalars:

$answer = 40;	# Integer
$Answer = 41;	# PHP is case-sensitive
$ANSWER = 42;	# PHP is still case-sensitive
$pi = 3.1417;	# Decimal
$animal = "dog";	# Text
$animal = 'dog';	# Using single or double quotes to denote your string
$animal_text = "dog \n cat \n mouse\n"; # Putting line breaks in your string

Remember: PHP is case-sensitive, so keep that in mind. You might try keeping all my variables in lower-case. It's one less thing you have to worry about. This is one tip that I keep forgetting when I write my scripts.

PHP excels when it comes to strings and text, so it's easy to concatenate text together of drop the value of a variable inside another. You can either drop them in specific places in the text, or you can build them using the '.' operator.

$x = 3;
$y = 8;
$sum = $x + $y;
$response = "The sum of $x and $y is $sum\n";
print $response;

# I could also have just explicitly printed the response:
print "The sum of $x and $y is $sum\n"

# Remember Mad Libs?
$adj1 = "dark";
$adj2 = "stormy";
$noun1 = "night";

print "Chapter One: It was a $adj1 and $adj2 $noun1\n";
For the above make sure you use the double quotes (") to delineate the string. Single quotes (') don't let you evaluate vars inside of them, so you have to do something like:
print 'Chapter One: It was a '.$adj1.' and '.$adj2.' '.$noun1.'\n';
Remember that the period (.) is used to concatenate text:
# Building a name using the . operator
$firstname = "Daniel";
$lastname = "Rozin";
$fullname = $firstname." ".$lastname;

# I could have also written:
$fullname = "$firstname $lastname";

print "I know an art god named $fullname\n";
If you need to put a double quote or dollar sign in your string then use the backslash (\) character to escape them.
print "The \"Big Mac\" now costs \\\$2 due to lower interest rates and national obesity\n";


PHP File and Variable Naming Conventions   [top]
PHP likes to see file and variable names that are alphanumeric, or in PHP syntax [a-z0-9]. In filenames, you'll often see the use of the underscore "_" and the dash "-":

hello.php
first_ass.php   # The ass is short for assignment, silly
second-ass.php  # The ass is still short for assignment
ass2.php        # The ass is short for, well, you get the picture
2ass.php        # ... see above ...
However, do not start your filenames with a dash:
-new-ass.php
Remember: PHP files, like any web file (HTML, Perl, CSS, Javascript, etc) served by the ITP Stage server, are case-sensitive, which means if you create a file called "Hello.php", upload it to your dwd directory on Stage and you go to the url:
http://itp.nyu.edu/~[netId]/dwd/hello.php
you'll get a 404 File Not Found error because "hello.php" is not the same as "Hello.php".

For variables, much of the same naming conventions apply, except the dash "-" should never be used, since this also means the minus sign:

$title = "First Assignment";              # Fine
$first_ass_title = "First Assignment";    # Fine
$second-ass-title = "Second Assignment";  # No good
$ass2_title = "Second Assignment";        # Fine
Also, do not start your variable names with a number:
\$2nd_ass_title = "Second Assignment";  # No good
PHP has some special reserved functions for \$1, \$2, et al.


PHP and HTML Output Basics   [top]
The whole point of using PHP to make web pages is that you can easily inject the values of PHP variables or make decisions about what blocks of HTML to print and have the PHP and HTML live in the same document. A simple PHP shortcut is this syntax:

<?php
$name = "Chris";
?>

The stupidest name I can think of is <b> <?= $name ?> </b>

so to quickly sub a PHP value in HTML, use the <?=$name_of_var?> syntax.

Of course, all of this can be done without leaving PHP:

<?php
$name = "Chris";

print "The stupidest name I can think of is <b> {$name} </b>";
?>

In this case, we just used a print statement and encased the variable in braces in the text. The braces are optional but are important if you need a variable to abut against some other text:

<?php
$closing_time = "4:00";

print "Closing time is {$closing_time}am";
?>

One other method I find very handy is the echo() method which, while very similar to the print() method, also lets you define a label at the beginning of the text you want to print, and then lets you mix HTML and PHP variables until you write the label once more (in this case "END" is the label). This is known as the heredoc syntax:

  • PHP Manual - Strings and Heredoc syntax
  • but watch out as it is finicky about whitespace - the opening label (in this case "END"), must be followed immediately by a newline, and the end label (in this case "END") must appear at the very beginning of its line and must be the only statement on that line

    <?php
    $prof_name = "Chris";
    $my_name = "Bob";
    $excuse = "my dog pressed control-alt-delete on my PowerBook";
    $late_day = "Friday";
    
    echo <<<END
    Dear $prof_name,<br>
    <p>
    This is $my_name writing you.  I am really sorry but I couldn't do my assignment.
    Unfortunately, $excuse, so I'll have for you by $late_day.
    <p>
    Sorry about that,<br>
    $my_name
    END;
    ?>
    
    Thus, the following are no good:
    <?php
    
    echo <<<END
      This is a statement I want to print
      END;
    
    if ($cmd=="print it")
    { echo <<<END
      This is a statement I want to print
    END; }
    ?>
    
    The proper syntax for the above is:
    <?php
    
    echo <<<END
      This is a statement I want to print
    END;
    
    if ($cmd=="print it")
    { echo <<<END
      This is a statement I want to print
    END;
    }
    ?>
    
    Another way to do the above example without using the echo() method is to simply switch back to HTML and then sub the PHP vars while in HTML:
    <?php
    $prof_name = "Chris";
    $my_name = "Bob";
    $excuse = "my dog pressed control-alt-delete on my PowerBook";
    $late_day = "Friday";
    ?>
    
    Dear <?=$prof_name?>,<br>
    <p>
    This is <?=$my_name?> writing you.  I am really sorry but I couldn't do my assignment.
    Unfortunately, <?=$excuse?>, so I'll have for you by <?=$late_day?>.
    <p>
    Sorry about that,<br>
    <?=$my_name?>
    


    Catching Errors   [top]
    PHP on Stage is configured to reveal minimal information when errors occur, so we need to have two-pronged approach. The following lines will help us catch a variety of errors, especially when we start connecting to our database:

    error_reporting(E_ALL ^ E_NOTICE);
    ini_set('display_errors', 1);
    
    Unfortunately, if you have a syntax error in your script (say you miss a ";" at the end of a statement), the following lines will never actually execute and thus, the error messages that are produced will not be sent to the browser. However, they are present if you SSH to Stage and run it from the command line. So if the name of your script is "test.php", then simply navigate to the directory on Stage where it lives and type:
    php test.php
    


    If-Then Statements   [top]
    You can create a lot of great stuff simply through setting variables and using If-Then statements to control the flow of your logic. The basic format is:

    if ([some condition is true])
    {	# Create some functionality here
    }
    elseif ([some other condition is true])
    {	# Create some other functionality here
    }
    else
    {	# Use this if you need to catch all the other cases
    }
    

    Common tests in an if statement are:

    # Comparing numbers using "=="
    if ($age==10)
    {	# Integer equality test
    	print "You are 10 years old!\n";
    }
    if ($age!=10)
    {	# Integer inequality test
    	print "You are not 10 years old.\n";
    }
    if ($age>10)
    {	# Integer greater than test
    	print "You are greater 10 years old.\n";
    }
    if ($age<10)
    {	# Integer less than test
    	print "You are less than 10 years old.\n";
    }
    
    # Comparing strings using "=="
    if ($favorite_team=="Yankees")
    {	# String equality
    	print "Get me a giant foam hand the next time you're at the Stadium.\n";
    }
    if ($favorite_team!="Yankees")
    {	# String inequality
    	print "Not a Yankees fan, eh?  I am a Mets fan myself.  Oy!\n";
    }
    
    # Comparing strings using strcmp()
    if (!strcmp($name,"Eli"))
    {	# String equality
    	print "You have the same name as the NY Giants QB.\n";
    }
    elseif (strcmp($name,"Eli")>0)
    {	# $name is greater than Eli
    	print "Your name is lexically greater than the Giants QB.\n";
    }
    else
    {	# $name is less than Eli
    	print "Your name is lexically lesser than the Giants QB.\n";
    }
    
    # Comparing strings case-independently using strcasecmp()
    if (!strcasecmp($name,"Eli"))
    {	# String equality
    	print "Your name could be Eli, eli, eLi, eLI.\n";
    }
    
    # Using the empty() function to determine if a value was given
    if (empty($favorite_team))
    {	# Blank value
    	print "Hmm... you don't seem to have a favorite team.\n";
    }
    if (!empty($favorite_team))
    {	# Non-blank value - means that something is there
    	print "Hooray!  You have a favorite team.\n";
    }
    


    Arrays   [top]
    As for arrays, an array is just an ordered set of scalars. It could be numbers, strings, or you can have both in the same list. Arrays can either be indexed by number (often called a "normal" array), or by a string (commonly called an "associative array" or a "hash"). Here's the firstnames of the Beatles in a normal array:

    # Array Indexed by Number or Normal Array
    $beatles = array("John","Paul","George","Ringo");
    
    # Another way to define the same thing
    $beatles[0] = "John";
    $beatles[1] = "Paul";
    $beatles[2] = "George";
    $beatles[3] = "Ringo";
    
    # Array Indexed by String or Associative Array
    $beatles_fullnames = array(
    	"John"   => "John Lennon",
    	"Paul"   => "Paul McCartney",
    	"George" => "George Harrison",
    	"Ringo"  => "Ringo Starr"
    );
    
    # Another way to define the same thing
    $beatles_fullnames["John"] = "John Lennon";
    $beatles_fullnames["Paul"] = "Paul McCartney";
    $beatles_fullnames["George"] = "George Harrison";
    $beatles_fullnames["Ringo"] = "Ringo Starr";
    

    Note that normal arrays use brackets around the index (i.e. [0] or [1]) and the first index is 0. Associative arrays also use brackets around the index (i.e. ["John"] or ["Paul"]).


    Basic Statements   [top]
    PHP has all of the basic programming constructs of other languages. Let's look at this example:

    <?php
    
    # Make sure we display errors to the browser
    error_reporting(E_ALL);
    ini_set('display_errors', 1);
    
    # Array Indexed by Number or Normal Array
    $beatles = array("John","Paul","George","Ringo");
    
    # Let's loop through and find the Beatle
    $i = 0;
    foreach ($beatles as $firstname)
    {	if ($firstname=="John")
    	{	print "I found John!  He's at $i <br>\n";
    	}
    	elseif ($firstname=="Paul")
    	{	print "I found Paul!  He's at $i <br>\n";
    	}
    	elseif ($firstname=="George")
    	{	print "I found George!  He's at $i <br>\n";
    	}
    	elseif ($firstname=="Ringo")
    	{	print "I found Ringo!  He's at $i <br>\n";
    	}
    	else
    	{	print "Hmm, apparently there's a 5th Beatle... <br>\n";
    	}
    	
    	$i++;
    }
    
    ?>
    

  • Class #2 Example Script - Beatles - Demo | Source Code


    Looping Through Arrays   [top]
    So then, how do we loop through the contents of a normal or associative array? This will be important to know when we start collecting user input.

    For normal arrays, if you just need the values and not the indexes, you can use foreach:

    $beatles = array("John","Paul","George","Ringo");
    
    foreach ($beatles as $firstname)
    {	print "$firstname\n";
    }
    
    If you do need the index, you can use a classic "for" loop. The upper bound can be found on the fly using the count() function, which returns the number of elements in the array:
    $beatles = array("John","Paul","George","Ringo");
    
    for($i=0; $i<count($beatles); $i++)
    {	print "index $i is $beatles[$i] \n";
    }
    
    For associative arrays, the foreach method is the most common:
    $beatles_fullnames = (
    	"John"   => "John Lennon",
    	"Paul"   => "Paul McCartney",
    	"George" => "George Harrison",
    	"Ringo"  => "Richard Starkey"
    );
    
    foreach ($beatles_fullnames as $nickname => $fullname)
    {	print "$nickname is the nickname of $fullname \n";
    }
    


    Functions   [top]
    Functions can be used to segment off certain functionality that needs to be performed repeatedly. That way, you don't have to keep writing the same code over and over again. For example, if we need to repeatedly bold certain text, we could write a subroutine to perform this functionality:

    ################################################
    # Add HTML bold tags to a string
    ################################################
    function bold_this($input)
    {
      $local_string = "<b>" . $input . "</b>";
      return ($local_string);
    }
    

    By creating a new variable inside the function, $local_string, and using the return() method, we don't actually alter the $input string. This lets the user decide whether the original string should be altered or not when we call it in the main script:

    $original_string = "The Boldly Dan O'Sullivan";
    
    # Put newly bolded version in its own variable
    $newly_bolded_string = bold_this($original_string);
    
    # The original variable will now hold the bolded version
    $original_string = bold_this($original_string);
    
    We can also just use it in context
    $name = "The Boldly Dan O'Sullivan";
    
    print "The boldest dude I know is ". bold_this($name) . "<p>";
    
    PHP has a multitude of built-in functions which we will explore as the semester progresses.


    Obtaining Form Input   [top]
    One of the most important aspects of using PHP to create dynamic web pages is the reception and parsing of variables that are passed either from an HTML form or as part of the URL string. There are several special global associative arrays that PHP gives us for free, $_SERVER, $_GET, and $_POST:

  • Global Array Listing | Source Code On the URL string of the browser, we can define name-value pairs (like the contents of an associative array) and pass them to our PHP script via the GET method using the syntax:

    http://itp.nyu.edu/~[netId]/dwd/foo.php?name1=value1&name2=value2
    
    or
    
    http://itp.nyu.edu/~[netId]/dwd/class02-ttt.php?v1=x&v5=o&v9=x
    
    or
    
    http://itp.nyu.edu/~cs220/dwd/class02-math1.php?x=2&y=5&cmd=add
    

  • Tic-Tac-Toe on the URL String | Source Code

    For the POST method, we provide an HTML form and let the user "submit" the values such that they are not seen by the user on the URL string but are passed in the same manner as the GET method.


    GET and POST in a Simple Math Example   [top]
    The following examples illustrate the difference between GET and POST and provide a brief introduction to the use of HTML form widgets to allow the user to input information.

  • Math on the URL String | Source Code
  • Math Using HTML Form | Source Code
  • Math Using HTML Form w/Persistence | Source Code
  • Math Using HTML Form w/Persistence, Formatting | Source Code
  • Math Using Different HTML Form | Source Code
  • Math Using Different HTML Form w/Persistence | Source Code


    Types of HTML Form Widgets   [top]
    Part of the HTML specification allows for you to create widgets that can accept user input that can be passed to your PHP script. A form is created when you place widgets within the opening <form> and the closing </form> tag. Only widgets that are contained within the form will pass their values to your PHP script. You can have multiple forms in one web page that submit to either the same or different PHP scripts, but for now, we'll just focus on one script containing one or more widgets. Here's a list of some of the ones I find most useful:

    <form></form>
    <form action="$script_name" method="POST" enctype="application/x-www-form-urlencoded">
    Creates all forms
    
    <select name="NAME"></select>
    <select name="state_id"></select>
    Creates a pulldown menu 
    
    <option value="VALUE" [selected]>NAME
    <option value="1">Delaware
    <option value="2" selected>Massachusetts
    Sets off each menu item 
    
    <textarea name="NAME" cols=40 rows=8></textarea>
    <textarea name="new_blog_message" cols=40 rows=8>A paragraph could go</textarea>
    Creates a text box area. Columns set the width; rows set the height. 
    
    <input type="checkbox" name="NAME" checked>
    <input type="checkbox" name="subscribed">Check here if you wish to receive our newsletter
    Creates a checkbox. Text follows tag. 
    
    <input type="radio" name="NAME" value="VALUE" [checked]>
    <input type="radio" name="likes_ice_cream" value="Yes">Yes
    <input type="radio" name="likes_ice_cream" value="No" checked>No
    <input type="radio" name="not_good_with_napkins" value="1" checked>Yes
    <input type="radio" name="not_good_with_napkins" value="0">No
    Creates a radio button. Text follows tag 
    
    <input type="text" name="NAME" value="VALUE" size=20>
    <input type="text" name="firstname" value="Christopher" size=20 maxlength=128>
    Creates a one-line text area. Size sets length, in characters.
    
    <input type="password" name="NAME" value="VALUE" size=20>
    <input type="password" name="pw" value="" size=20 maxlength=128>
    Same as a text field except that asterisks are shown instead of actual chars.
    
    <input type="submit" name="NAME" value="VALUE">
    <input type="submit" name="dataAction" value="Submit">
    Creates a Submit button
    
    <input type="hidden" name="NAME" value="VALUE">
    <input type="hidden" name="cart_id" value="4F3HDGS36251">
    Creates a hidden field that you can use to hold text.  Not visible to user. 
    
    <input type="image" border=0 name="NAME" src="images/home/submit_b.gif">
    Creates a Submit button using an image 
    
    <input type="reset">
    Creates a Reset button 
    

    So for example, a simple login screen might look like the following:

    <form action="login.php" method="POST" enctype="application/x-www-form-urlencoded">
    Username: <input type="text" name="un" value="" size=20 maxlength=32> <br>
    Password: <input type="password" name="pw" value="" size=20 maxlength=32> <br>
    <input type="submit" name="dataAction" value="Login">
    </form>
    

  • Simple HTML Form Values | Source Code
  • Reading & Writing HTML Form Values #1 | Source Code
  • Reading & Writing HTML Form Values #2 | Source Code
  • Multiple Checkbox Example | Source Code


    Basic PHP Form Processing   [top]
    In the scripts presented in this class, we'll see that this is a case where when a script is first called, it presents an empty form. Once you fill in the form and hit submit, the submitted values are sent to the same script that originally presented the form. In this case, we need to make our PHP script dual purpose, such that it knows when it's first been called, and then when a form has actually be submitted. The easiest way to do this is to check whether the submit button was pressed. This can easily be achieved using the following code:

    $submitName = "dataAction";
    $submitValue = "Submit";
    
    if ($_POST[$submitName]==$submitValue)
    {	# Form was submitted so do whatever processing is needed here
    
    }
    
    We just need to make sure that someweher in our form, preferably at the end, we write our submit widget like so:
    <input type="submit" name="<?=$submitName?>" value="<?=$submitValue?>">
    
    Thus, the general logic flow for a PHP script using this methodology would be as follows: It's important to show any timely results at the top of the page because this is what the user sees first when they submit the form, and you want to let them know right away that something has happened.


    A Sample PHP-HTML Template   [top]
    So now, we have all the elements for a script that can read input variables that are sent from HTML widgets. We can even put the HTML widgets, from which we are reading, in the same script, such that our script just calls itself when the HTML form is submitted.

    <?php
    
    #########################################################
    # template.php - Base template for PHP script
    #########################################################
    $scriptName = $_SERVER['PHP_SELF'];
    $pageTitle = "put the title of your web page here";
    
    # Make sure we display errors to the browser
    error_reporting(E_ALL ^ E_NOTICE);
    ini_set('display_errors', 1);
    ?>
    
    <html>
    <head>
    <title><?=$pageTitle?></title>
    <style type="text/css">
    body {
    	font: 13px arial;
    	color: #000;
    	background-color: #fff;
    	padding: 10px;
    	margin: 0px;
    }
    </style>
    </head>
    <body>
    <b><?=$pageTitle?></b>
    <p>
    <form action="<?=$scriptName?>" method="POST" enctype="application/x-www-form-urlencoded">
    </form>
    </body>
    </html>
    


    Basic File I/O   [top]
    PHP gives us a way to read and write files on the server, or even test for their existence. For writing, the basic premise is that we first create a pointer to the file we want to either write or append, and then use that pointer to perform the desired action. If we want to test whether or not the file exists, we can do something like this:

    $file = "/home/[netId]/public_html/foo.txt";
    
    # Test if the file physically exists on the server
    if (file_exists($file))
    {	print "The file $file exists";
    }
    
    If we want to read this file and send it to the browser, here's one easy way:
    $file = "/home/[netId]/public_html/foo.txt";
    
    $content = file_get_contents($file);
    print "Content is $content";
    
    or if you need to read one line at a time:
    $file = "/home/[netId]/public_html/foo.txt";
    
    $file_ptr = fopen($file,"r"); # "r"=read, "a"=append, "w"=overwrite
    while (!feof($file_ptr))
    {	$line = fgets($file_ptr);
    	print "$line <br>";
    }
    
    If we want to write or append to a file:
    $file = "/home/[netId]/public_html/foo.txt";
    $text = "This is some text I want to save";
    
    $file_ptr = fopen($file,"a"); # "a" = append to existing content, "w" = overwrite
    fwrite($file_ptr,$text);
    fclose($file_ptr);
    

  • Class #2 Example Script - Basic File I/O - Demo | Source Code


    A Page That Changes Each Time   [top]
    Here's an example of a script that spits out a random quote everytime you access it. You can also explicitly ask for a particular quote. It also prints out the time.

  • Class #2 Example Script - Quote Generator - Demo | Source Code


    Related Resources   [top]

    Recommended Reading/Reference

  • Web Database Applications with PHP & MySQL
    PHP Variables, Operators, Expressions, Logic Flow (pps. 16-36), Functions and Include Files (pps. 45-56), Arrays, Strings and Dates (pps. 57-71, 76-87, 97-103)

    PHP Books

  • Learning PHP 5 By David Sklar
  • Programming PHP, Second Edition By Kevin Tatroe, Rasmus Lerdorf, Peter MacIntyre

    On-Line PHP Reference

  • Official PHP Manual

    HTML Reference

  • WebMonkey.com

  • Home  ·  Syllabus  ·  Submissions  ·  Resources
    © 2003-2013. All rights reserved.