Connecting Processing scripts to the Internet using PHP

Click on the image to change the lines:

 

 
The above image is produced by a processing sketch. Each line drawn is given a random colour generated by a PHP program running on a web server. Each time the image is clicked, a PHP program running on the server generates 40 random numbers.The processing script then draws 40 lines with the colour determined by the numbers the PHP script outputs. This could be done using just processing and no PHP whatsoever , but the purpose of this post is to demonstrate how information obtained from a PHP program can be used in Processing. This opens up the possibility for some really cool real time data visualisation using Processing.

Here is the Processing script used:

int draw_lines = 1;

void setup()
{
size(850, 400);
}

void draw()
{

if (draw_lines == 1) {
String[] data = loadStrings("https://www.wattnotions.com/phpstuff/rand_numbers.php");
int[] nums = int(split(data[0], ','));
int i = 0;
int linewidth = width/40;
strokeWeight(linewidth);
for(int h=0; h<nums.length; h++) {
i = i + linewidth;
stroke(nums[h]);
line(i,height,i,0);
}
draw_lines = 0;
}

}

void mouseClicked() {
draw_lines = 1;
}

The main things to notice about how this program works are the lines :

String[] data = loadStrings("https://www.wattnotions.com/phpstuff/rand_numbers.php");
int[] nums = int(split(data[0], ','));

The PHP script is sitting on the server I am using for hosting this website. Its location is this directory: public_html/php_stuff/rand_numbers.php. This means it can be accessed at the following link : https://www.wattnotions.com/phpstuff/rand_numbers.php If you click on that link you will see the output of the very basic PHP script. It generates 40 random numbers in the range 0-255. Each number is seperated by a comma. To get this information into processing, the loadStrings function can be used. Just point it to the location of the PHP script and it will return whatever the script outputs. Then to parse this string into individual numbers the split function is used.

Here is the PHP script used to generate the random numbers:

<?
for($i=0; $i<40; $i++) {
echo rand(0,255).",";
}
?>

Leave a Reply

%d bloggers like this: