The purpose of this tutorial is two-fold. Number one, we’re going to demonstrate how all of the basic fundamental concepts you’ve learned with Processing (variables, conditionals, loops, functions, objects, arrays) extend to programming in other languages. Second, we’ll see how there are certain types of tasks that you can farm out to a server-side script (in this case, written in PHP) that cannot be done easily inside of your Processing code itself.

Thanks to Shawn Van Every and Dan O’Sullivan, this tutorial is based off of material from Shawn’s quick and dirty PHP as well as Dano’s PHP sample code.

What is PHP?

PHP (which originally stood for “Personal Homepage”, but now stands for “Hypertext Preprocessor”) is a scripting language designed for creating dynamic web pages. What does it mean for a web page to be dynamic? If you are familiar with basic HTML, you know that you can “mark up” a web page to have specific formatting with a tag structure. Something like:

<html>
  <head> 
    <title>Your Page's Title</title>
  </head>
  <body>
    The <strong>content</strong> of your <em>web page</em>.
  </body>
</html>

Here’s what the above HTML actually looks like in your web browser: basic.html.

The key thing to notice here is that no matter how many times you hit the refresh button, this web page will never vary. It is completely static (sometimes referred to as “flat” html). By introducing data and logic (i.e. programming) into a web page (with PHP), you can create web pages that look different based on some set of inputs (a database, what a user types into a form, random numbers, etc.). To integrate PHP inside of an html page, you must:

  • Make sure your web server supports PHP
  • Create a file with the PHP extension, i.e. “index.php” or “mypage.php”
  • Write HTML as normal, but include any PHP code inside of: <? PHP HERE ?>

Here’s an example of a PHP page that displays a random number between 0 and 10 each time you load the page: random.php, source: random.php.txt.

<html>
  <head> 
    <title>Random number between 0 and 10</title>
  </head>
  <body>
     A random number: <? echo rand(0,10); ?>
  </body>
</html>

Notice how this looks identical to our “flat” html with one exception: <? echo rand(0,10); ?> In between “<?” and “?>” is the PHP code. “echo” means print, i.e. we want to see whatever comes after echo in the browser itself. rand(0,10) is a call to a function that returns a random number between 0 and 10. This is no different than random() in Processing. The documentation for this function can be found on php.net: http://us2.php.net/manual/en/function.rand.php.

The Fundamentals in PHP

Now that we have a basic sense of why PHP exists in the first place and how we integrate PHP code into a web page, we can arrive at the happy moment where we see that all that fundamental programming stuff we learned with Processing applies to PHP (and pretty much all programming languages) too! (Also, in the example below, notice how “//” also indicates a comment in PHP.)

Variables

Differences with Processing:

  • All variables in PHP must start with a dollar sign: $
  • PHP does not require that you declare the data type for your variable!

Example:

// Declaring and initializing variables (no need to specify a data type!)
$x = 5;
$xspeed = 4.23;
$x = $x + $xspeed;
echo $x;
// Two strings
$name = "Zoog";
$title = "Cosmonaut";

echo $title . " " . $name;

Also, notice how in the above code a period — ‘.’ — is used to concatenate two Strings. In Java/Processing, the plus — ‘+’ — operator is used.

Conditionals

Conditionals (if, else if, else) are exactly the same as in Processing!

$x = rand(0,10);
// Basic conditional in PHP
if ($x > 5) {
  echo $x . " is greater than 5";
} else {
  echo $x . " is less than or equal to 5";
}

Loops

Loops (for, while) are exactly the same as in Processing!

// Loop in PHP
for ($i = 0; $i < 10; $i++) {
  echo $i;
}

Arrays

There are several differences with how arrays work in PHP:

  • Again, just like with variables, you are not required to specify the the data type for an array
  • You do not have to explicitly declare the size of the array in advance! This makes it especially easy to just add elements to the end of an array
  • .

  • PHP allows for a special “for each” syntax to loop through an array.
  • PHP allows for something called an associative array. An associative array is a list of values where each value is referenced by a “key” (String) rather than an index (integer). In other words, instead of numbering the elements of your array from 0 to 9 (10 elements total), you can name the elements of your array. Array element “fred”, array element “sue”, array element “bob”, etc. There are certain instances where this is especially convenient. Note that you can also do this in Processing, with the use of a HashMap.
  • You can get the size of an array with the sizeof() function

Here is some example array code in PHP that covers the above items:

// Creating an array
$nameList = array("Joe","Jane","Bob","Sue");
echo $nameList[2];

// Adding an element to the end of that array
$nameList[] = "Zoog";
echo $nameList[4];

echo "<br><br>";

// Create an array with a loop
for ($i = 0; $i < 10; $i++) {
  $nums[$i] = rand(0,10);
}

// Using foreach syntax
foreach ($nums as $value) {
  echo $value . " " ;
}

// Getting the size of an array
echo "<br><br>The size of the array is " . sizeof($nums);

// An associative array
$studentIDs["Joe"] = 23;
$studentIDs["Jane"] = 41;

Functions

You can write your own function in PHP:

// Defining a function
function printDate() {
 echo "The Date and Time is: ";
 $today = date(DATE_RFC822);
 echo $today;
}

Objects

You can also write classes and make objects in PHP, with some differences:

  • Variables must be declared as public or private
  • The constructor is always named: “__construct”
  • Instance variables need to be referred to as: “$this->varname”.
// Defining a class
class Human {
  // Declaring instance variables
  public $firstname = "default";
  public $height = 0;
  
  // Writing a constructor
  function __construct($n) {
    // Notice the use of $this->varname
    $this->firstname = $n;
    $this->height = rand(5,6);
  }
   
  // A function
  function show() {
    echo "<br><br>" . $this->firstname . " is " . $this->height . " feet tall.";
  }
}

Creating an object and calling its methods is easy, the only difference is the use of the “->” syntax — i.e. object->function() — instead of what we are used to in java: object.function().

// Creating an object
$frank = new Human("Frank");
// Calling a function on the object
$frank->show();

Here is sample code for all of the above fundamental programming concepts: fundamentals.php.txt.

Execute the script: fundamentals.php

PHP and forms

A very common use of PHP is to receive data from a form and generate output accordingly. Let’s look at an example html form: form.html

<html>
  <head>
    <title>A Simple HTML Form</title>
  </head>
  <body>
    <form action="getform.php" type="get">
    Name: <input type="text" name="name"><br>
    Mood:
    <select name="mood">
      <option value="sad">Sad</option>
      <option value="happy">Happy</option>
    </select>
    <br>
    <input type="submit" value="Submit Me">
    </form>
  </body>
</html>

Notice how the form’s “action” is defined as “getform.php.” This means that when the user hits submit on the form, the data will be sent via an HTTP Get request. PHP can then ask for that data using the built-in variable: $_GET. $_GET is technically an associative array, and the values can be retrieved by referencing the form’s input name, i.e.:

$name = $_GET["name"];

Here is a simple example where the resulting HTML output depends on the form’s input: getform.php, source: getform.php.txt.

<html>
  <head>
    <title>The Form Output</title>
  </head>
  <body>
  
  <?
    // Get the stuff entered into a form
    $name = $_GET["name"];
    $mood = $_GET["mood"];
    
    echo $name . ", ";
    
    // Based on what was selected in the form, pick an output
    if ($mood == "happy") {
      echo " I am jealous of your happiness.";
    } else {
      echo " why so glum?";
    }
  ?>
  
  </body>
</html>

This data does not have to come from an HTML form. If you look closely at the browser address bar, you’ll notice that it looks like this:

http://www.learningprocessing.com/php/getform.php?name=Fred&mood=happy

You can manipulate the query string yourself (getting used to this is important because when we get to integrating PHP with Processing, you’ll need to create the query string without a web form.) The syntax for url query strings is:

mypage.php?name1=value1&name2=value2&name3=value3

Using PHP for Persistence

One of the great things we can use PHP for is persistence. Since a PHP script is executed on the server (as opposed to a Processing applet which runs client side), it can read and write data directly to and from the server rather easily. The first thing we need to do is find built-in PHP functions that allow us to read from and write to a file. All of the built-in functions available to you in PHP (we’ve seen a few so far: date(), rand()) can be found by searching php.net. The functions we need for file I/O are:

  • fopen() — opens a file (or a url). When you open the file, you should declare your intentions, i.e. do you plan on reading, writing a new file, appending to an old file, etc. To write to a file, you pass in the argument: ‘w’, to append: ‘a’, read-only: ‘r’, etc.
  • fread() — returns the content of a file
  • fwrite() — writes content to a file
  • filesize() — returns the size of a file
  • fclose() — closes a file (should be called when you are finished reading or writing)

Using the above built-in functions, we can write a generic function to write to a file:

// Function to write to file
function writeData($filename,$content){
  $dest = fopen("$filename", 'w') ;
  fwrite ($dest,$content);
  fclose($dest);
}

And one to read from a file:

// Function to read from file
function getData($filename){
  $size = filesize ($filename);
  $src = fopen ($filename, 'r');
  $content = fread ($src,$size);
  fclose ($src);
  return $content;
}

So, let’s take a simple situation where our text file looks like this: data.txt.

0,1

Let’s recreate Example 5-6: Bouncing ball, only instead of Java applet, we’ll have a simple web page with the letter X. Each time the page is refreshed, the PHP script reads the two numbers from the text file and places the “X” accordingly — the first number is its horizontal location and the second number is its direction of movement. Here are our steps, along with the code:

1. Read in the data from the file:

$content = getData("data.txt");

2. PHP also has a split() function to chop up a string into an array:

$vals = split(",",$content);
$x = $vals[0];
$dir = $vals[1];

Notice how we don’t have to do any string to integer conversion in PHP!

3. Move the letter and display it:

$x += $dir;

if ($x > 5 || $x <= 0){
  $dir *= -1;
}

for($i = 0; $i < $x; $i++){
  echo " "; // A space
}

echo "X";

4. Write new data back out to the file:

writeData("data.txt","$x,$dir");

Notice here how we can put variables directly into a String (between quotes). We don't actually have to concatenate a String with "."!!

Here is the PHP script in action: bounce.php and the source: bounce.php.txt.

A word of caution: anyone can access and modify the data on the server via get. Anything passed to php via a url query string leaves open the potential for mischief and you should take appropriate cautions, such as limited file reads / writes to a certain directory, etc.

Using PHP for Persistence with Processing

The same technique we used for persistence from one refresh to another of a web page can be used with a Processing sketch (with loadStrings() replacing the web browser). Let's consider a PHP script that can do three things:

  • Read from a text file and write out the content
  • Append an (x,y) coordinate to a text file
  • Clear the text file of all content

The first thing we want to do is structure our PHP script to receive a command in the form of a URL query, i.e. these three queries will result in a different action:

  • loadstrings.php?type=load
  • loadstrings.php?type=save&x=100&y=100
  • loadstrings.php?type=clear

We can structure the PHP script to have a simple conditional based on the value of "type." In the code below, we first check to see if type has been passed in via the query string at all. We ask if $_GET['type'] "is set," using isset().

if (isset($_GET['type'])) {
  $type = $_GET['type'];
} else {
  $type = "null";
}

Next, based on the value of $type, we can execute different operations:

if ($type == "save") {
  // SAVE CODE GOES HERE
} else if ($type == "clear") {
  // CLEAR CODE GOES HERE
} else if ($type == "load") {
  // LOAD CODE GOES HERE
} else {
  echo "This PHP script requires a query string!";
}

Processing can then use loadStrings() to ask the PHP script to perform various tasks. For example, saving a coordinate when the mouse is clicked:

void mousePressed() {
  String[] lines = loadStrings("http://www.learningprocessing.com/php/loadstrings.php?type=save&x=" + mouseX + "&y="+mouseY);
}

Or clearing the file when a key is pressed:

void keyPressed() {
  String[] lines = loadStrings("http://www.learningprocessing.com/php/loadstrings.php?type=clear");
}

And, of course, loading the current text in the file and drawing something based on the data in that file:

String[] lines = loadStrings("http://www.learningprocessing.com/php/loadstrings.php?type=load");
for (int i = 0; i < lines.length; i++) {
  int[] vals = int(split(lines[i],","));
  rectMode(CENTER);
  stroke(0);
  fill(175);
  rect(vals[0],vals[1],10,10);
}

Check out the full example with PHP source here:

http://www.learningprocessing.com/tutorials/php/php-persistence/

Errors

PHP may not be set up to show all errors. You can add the following two lines to enable error output while you are developing:

ini_set('error_reporting', E_ALL);
ini_set('display_errors', true); 
  • http://things.sansumbrella.com/ David

    This is a great intro to PHP, and the suggestion for how to use PHP along with Processing is fantastic. Very clear and helpful for adding another level of sophistication to processing applets.

  • Florian Jenett

    Hi Daniel!

    Nice tutorial, my students are gonna love that.

    One sidenote, you should maybe put a mild warning that anyone can access and modify the data on the server via get. All variables (anything) passed to php via the url or put-requests should be treated as being suspicous and file reads / writes should be restricted to a certain directory.

    F

  • error
  • http://www.iqdupont.com Quinn DuPont

    Processing and PHP seem like such a natural fit, thanks!

    Coming from a PHP background to Processing is making me think of the possibilities, I’m glad you jogged some ideas for me.

  • Stefan Nowak

    This tutorial perfectly illustrates the way of how Processing can request from PHP! Or in other words: How to initiate inter process communication from Processing to PHP!

    I want to add a hint, for people who might ask themselves:

    Q: How can I send events/data from PHP to Processing? In other words: How can I initiate communication from PHP to Processing?
    A: Just create a Server object in Processing and then send data to it from within PHP via its various stream access functions like fwrite().

    I used the tutorial at:
    http://processing.org/learning/libraries/chatserver.html

    To test the server reaction I started a telnet session in the command line:

    $ telnet localhost 10002

    An interactive session opened. I wrote various lines, which I each submitted via the RETURN key. Within Processing the sent lines immediately appeared. It works fine!

    More on PHP streams, etc:
    http://www.php.net/manual/en/intro.stream.php
    http://www.php.net/manual/en/function.fwrite.php

  • http://larawaller.posterous.com/ Lara

    Holy wow! This is simply amazing! You’ve outdone yourself with another great post! Just what i was looking for:)

  • Guest

    yututr

  • Rak

    what the fuck is this

  • sarabjeet singh

    Great post indeed and thanks for all the information, it was very helpful i really like that you are providing information on PHP and MYSQL with basic JAVASCRIPT,being enrolled in http://www.wiziq.com/course/5871-php-mysql-with-basic-javascript-integrated-course i was looking for such information online to assist me on php and mysql and your information helped me a lot. Thanks.

  • chris!

    This tutorial get’s five stars! Nice job!

    Note to those using php 5: split() has been deprecated. Use explode() instead.

    Also, I had an issue with moving the X using php. The tutorial (section #3: Move letter and display it) says:

    echo ” “; // A space

    This didn’t work for me. Could be that i was using Firefox. Don’t know, but it didn’t work. So instead of a just space, i used a “.” with a space:

    echo ” .”; // A period with space

    Hope this helps others. Those notes aside (programming can be quirky sometimes as new changes to language comes out), I still give this tutorial 5 stars!

  • Hjoaco Mg

    Master Daniel, how could parse a external php file?

  • shiffman

    could you be more specific?

  • Hjoaco Mg

    how to parse a website writte in php, example: http://www.website.com/internal.php.

  • shiffman

    you can use loadStrings(), you cannot access the php code unless you are the author, only the generated HTML.

  • Hjoaco Mg

    i try access html.

    my intention is generate json file.

    when I have more time I’ll try to generate it with nodejs and read with processing.
    Thank master Daniel.

  • kamesh

    This is for the admin who handling this site. just insert this line “overflow: auto;” in tag of screen.css on line number 23…….

  • Mital

    avi site hoy error na dhagla 6e.