Producing Participatory Media
Class 7 - July 22

Topics:

  • PHP 101
  • PHP with MySQL
  • File Uploading
  • FFMPEG
  • Blip.TV API in PHP
  • YouTube API in PHP


  • PHP 101

    Basic HTML

    <html> <!-- Required for all HTML pages -->
    	<head> 
    		<title>The Top Bar Title</title>
    	</head>
    	<body>
    		Some information
    		<!-- A Comment Tag -->
    	</body>
    </html> <!-- Closing tag, required -->
    		
    Example 1

    Basic HTML with PHP
    PHP = Hypertext Preprocessor

    <html> <!-- Required for all HTML pages -->
            <head>
                    <title>The Top Bar Title</title>
            </head>
            <body>
                    Some information
    		<br> <!-- A line break -->
                    <!-- A Comment Tag -->
    		<?  // Denotes the start of PHP processing
            		echo "The Date and Time is: ";  // print a string, end with a semicolon
            		$mydata = "July 29, 2004"; // Assign a variable 
            		echo $mydata; // print the string variable
    		?> 
    
            </body>
    </html> <!-- Closing tag, required -->
    		
    Example 2
    Take note of the different comment styles.
    The "//" style within PHP and "<--" outside of PHP (normal HTML)
    Variables begin with "$".
    "=" are assignment.
    "echo" is the print function.
    ";" ends line of code.
    PHP files are saved with ".php" not ".html"

    PHP Functions
    Can occur anywhere in the page within "<? ?>" tags

    <?
    function printDate()
    {
    	echo "The Date and Time is: ";
    	$mydata = "Feb. 27, 2007";
            echo $mydata;
    }
    ?>
    <html>
            <head> 
                    <title>The Top Bar Title</title>
            </head>
            <body>
                    <? 
    			printDate();
                    ?>
            </body>
    </html>
    
    Example 3

    Built-in PHP Functions
    More than you can imagine: Everything from writing XML to creating images on the fly including creation of Flash files and running Java applications
    PHP.net is your best friend
    <?
    function printDate()
    {
            echo "The Date and Time is: ";
            $mydata = date("g:i:s A T D. M, j Y");
    	/*  -- Multiline comment
    	"date" is a built-in function that has some interesting formatting capabilities.
    	*/
            echo $mydata;
    }
    ?>
    <html>
            <head>
                    <title>The Top Bar Title</title>
            </head>
            <body>
                    <?
                            printDate();
                    ?>
            </body>
    </html>
    
    Example 4
    date page from the PHP Manual

    PHP with Forms
    PHP is ideal for generating HTML forms and even more so for dealing with data that comes back from forms.

    A Basic HTML Form
    <html>
            <head>
                    <title>A Basic HTML Form</title>
            </head>
            <body>
    		<form action="form_example.php" type="get">
    			First Name:<input type="text" name="first_name"><br>
    			Last Name:
    			<select name="last_name">
    				<option value="Smith">Smith</option>
    				<option value="Doe">Doe</option>
    			</select>
    			<br>
    			<input type="submit" value="Submit Me">
    		</form>
            </body>
    </html>
                    
    HTML Form Example

    Form Processing with PHP Dealing with data submitted via a form
    <?
            /* 
            Description: Helper function to get values from a form post (type="post" or query string (type="get")
            Returns: value of key or null on failure
            */
            function getPOSTorGETValue($key)
            {
                if (isset($_POST[$key]))
                {
                    $value = $_POST[$key];
                }
                else if (isset($_GET[$key]))
                {
                    $value = $_GET[$key];
                }
                else
                {           
                    $value = null;
                }    
                return $value;
            }
    ?>
    <html>
            <head>
                    <title>The Form Output</title>
            </head>
            <body>
                    <?
    			$first_name = getPOSTorGETValue("first_name");
    			$last_name = getPOSTorGETValue("last_name");	
    			echo "Your First Name is: " . $first_name . "<br>";
    			echo "Your Last Name is: " . $last_name . "<br>";
                    ?>
            </body>
    </html>
    
    Example Form Output




    File Uploads

    PHP can receive files that are uploaded through a browser.

    Below is a PHP page which enables that:
    <? echo "<?xml version=\"1.0\"?>\n"; ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html>
    	<head>
    		<title>File Upload Test</title>
    	</head>
    	
    	<body>
    		<h1>File Upload Test</h1>
    <?
    
    	ini_set('display_errors', true);
    	ini_set('display_startup_errors', true);
    	error_reporting(E_ALL);
    
    	// Limit what people can upload for security reasons
    	$allowed_mime_types = array("video/3gpp"=>"3gp", 
    								"audio/x-wav"=>"wav", 
    								"video/mp4"=>"mp4",
    								"video/3gpp2"=>"3g2",
    								"video/mpeg"=>"mpg",
    								"video/quicktime"=>"mov",
    								"video/x-quicktime"=>"mov",
    								"video/x-msvideo"=>"avi",
    								"image/jpg"=>"jpg",
    								"image/jpeg"=>"jpg",
    								"image/pjpeg"=>"jpg",
    								"image/png"=>"png",
    								"audio/vnd.wave"=>"wav"
    								);
    
    	// Make sure form was submitted
    	if (isset($_POST['form_submitted']) && $_POST['form_submitted'] == "true")
    	{
    		// Check the mime type
    		$allowed_types = array_keys($allowed_mime_types);
    		$allowed = false;
    		if (isset($_FILES['bytes']['type']))
    		{		
    			for ($i = 0; $i < sizeof($allowed_types) && !$allowed; $i++)
    			{
    				if (strstr($_FILES['bytes']['type'], $allowed_types[$i]))
    				{
    					$allowed = true;
    				}
    			}
    		
    			// If the mime type is good, save it..
    			if ($allowed)
    			{
    				$uploadfilename = time() . "_" . rand(1000,9999) . "_" . basename($_FILES['bytes']['name']);
    				// Make sure apache can write to this folder
    				$uploaddir = '/home/sve204/public_html/ppm_summer08/uploads/';
    				$uploadfile = $uploaddir . $uploadfilename;
    				$uploadrelativefile = 'http://itp.nyu.edu/~sve204/ppm_summer08/uploads/' . $uploadfilename;
    		
    				if (move_uploaded_file($_FILES['bytes']['tmp_name'], $uploadfile))
    				{
    					// Make sure the file isn't executable and you can delete it if you need
    					chmod($uploadfile, 0666);
    										
    					$subject = "";
    					$message_text = "";
    					
    					if (isset($_POST['subject']))
    					{
    						$subject = $_POST['subject'];
    					}
    					
    					if (isset($_POST['message_text']))
    					{
    						$message_text = $_POST['message_text'];					
    					}
    					
    					// Tell the user
    					echo "<p>Success <br /> <a href=\"" . $uploadrelativefile  . "\">" . $uploadrelativefile . "</a></p>";
    				}
    				else
    				{
    					echo "<p>Error on upload...!  Here is some debugging info:</p>";
    					var_dump($_FILES);
    				}
    			}
    			else
    			{
    				echo "<p>Type not allowed...! Here is some debugging info:</p>";
    				var_dump($_FILES);
    			}
    		}
    		else
    		{
    			echo "<p>Strange, file type not sent by browser...!  Here is some debugging info:</p>";
    			var_dump($_FILES);
    		}
    	}
    	else
    	{
    ?>
    		<form enctype="multipart/form-data" method="post" action="upload.php">
    			<p>
    				Title: <input type="text" name="subject" /><br />
    				Description: <input type="text" name="message_text" /><br />
    				<input type="file" name="bytes" />
    				<input type="hidden" name="form_submitted" value="true" />
    				<br />
    				<input type="submit" name="submit" value="submit" />
    			</p>
    		</form>
    <?
    	}
    ?>
    	</body>
    </html>
    
    Permissions

    The directory that files get uploaded to needs to be writeable by the user that runs the PHP script. In our case, on ITP's server, this is the "apache" user. In order to make the directory by apache, you need to either do the chmod 777 command via the command line application or use your SFTP software to make the change so that it is writeable by "others" or the "world".

    Try it: http://itp.nyu.edu/~sve204/ppm_summer08/upload.php

    More information:
    PHP - Upload Script Security



    FFMPEG

    FFMPEG is an open source piece of software that can open and encode many different types of media files. Generally it is run via the command line but there are front end interfaces for it on most operating systems.

    We have FFMPEG installed on our server and it can be used to transcode and create thumbnails for media files that are uploaded through PHP.

    Thumbnailing

    /usr/local/bin/ffmpeg -y -i inputfile -vframes 1 -f mjpeg -ss 10 -s 320x240 -an outputfile.jpg

    By way of explaination: /usr/local/bin/ffmpeg is the application itself, including the path, -y means overwrite without prompting the user, -i indicates that the next word is the input file, -vframes 1 means only create 1 frame of output, -f mjpeg means use the motion jpeg codec (really just a jpeg since we are only grabbing 1 frame), the -ss 10 means start at 10 seconds in, -s 320x240 means make the file 320 pixels wide by 240 pixels tall and -an means disable audio. The last word is the file to output to.

    In PHP

    exec("ffmpeg -y -i " . $inputfile . " -vframes 1 -f mjpeg -ss " . $position . " -s " . $size . " -an " . $outputfile, $output, $return);

    The above uses the PHP command "exec" which executes a command line application through PHP.

    Transcoding

    /usr/local/bin/ffmpeg -y -i inputfile -s 320x240 -ar 22050 outputfile.flv

    The difference in this command is that we are specifying an audio sample rate of 22050 for flash output and we are removing most of the options. Because we use an ".flv" extension on the file, FFMPEG knows what to do to encode the file.

    In PHP

    exec("ffmpeg -y -i " . $inputfile . " -s " . $size . " -ar 22050 " . $outputfile, $output, $return)

    More Information:
    FFMPEG Documentation

    Blip.TV API

    Blip.TV has a very nice platform for uploading and hosting video and it is free (for most uses). They allow you to cross post your video, they automatically transcode to Flash, they provide direct links to the files so you can do what you like with them (unlike YouTube) and they have a revenue sharing arrangement for ads served on the files.

    One other thing they have is a REST (Representational State Transfer) API which is accessed through normal HTTP connections using XML. You can learn quite a lot about the API and the capabilities of it on Blip's Wiki

    Thankfully, some enterprising individuals have come up with a simplified means to use portions of the API through PHP. The phpBlip package provides a nicer interface to developing applications that pull data from Blip, much the way the phpYoutube package allows for pulling data from YouTube.

    The easiest way to get started with the phpBlip package is to unpack it, upload it to your webserver and look at the example.php output.

    If you view the source of the example.php file you will see that there are two calls at the beginning to start using it:
    include("phpBlip.php");
    $phpBlip = new phpBlip();	
    	
    The first call includes the phpBlip class definition and related files. The second actually creates an object out of the class. This object is what can be used to query the blip site.

    There are two functions that can be used with the phpBlip object:

    find_posts which searches blips database for posts that match your parameters.
    Function definition:
    function find_posts($userid = null, $search = null, $explicit = false, $language_code = "en", $category = null, $license = null, $has_media = 1)
    	

    Example:
    $results = $phpBlip->find_posts();
    for ($i = 0; $i < sizeof($results); $i++)
    {
    	print_r($results[$i]);
    }
    	

    Of course, you can add in whatever parameters you would like:
    $results = $phpBlip->find_posts(null,"cats");
    for ($i = 0; $i < sizeof($results); $i++)
    {
    	print_r($results[$i]);
    }
    	

    The other function is:
    find_post which allows you to pull more information about an individual post (such as a link to file):
    print_r($phpBlip->find_post($some_post_id));	
    	

    Putting the two together allows you to do a bunch of different things for example:
    $vids = $phpBlip->find_posts(null, "test");	
    for ($i = 0; $i < sizeof($vids); $i++)
    {
    	$current_video = $phpBlip->find_post($vids[$i]["id"]);
    
    	for ($m = 0; $m < sizeof($current_video['media']); $m++)
    	{
    		if ($current_video['media'][$m]['link_type'] == 'video/x-flv')
    		{
    ?>	
    			<a href="http://itp.nyu.edu/~sve204/ppm_spring07/player.php?m=<?php echo $current_video['media'][$m]['link_href'] ?>"><? echo $current_video['title'] ?></a>					
    			<br><br>	
    <?
    		}
    	}
    }	
    	

    Example output