Introduction To Computational Media on the Web (ICM-W) : Week 5

Introduction to PHP

PHP stands for either the HyperText Preprocessor or Personal Home Page

PHP is a very useful language and can be used for many types of development. Primarily, though, it is used for web development (hence the name(s)). We will of course concentrate on using PHP for web development.

The big difference between PHP and what we have been learning (JavaScript) is that PHP is interpreted on a webserver instead of in a web browser. It is therefore considered a serverside language.

Basic HTML with PHP

<html>
        <head>
                <title>The Top Bar Title</title>
        </head>
        <body>
                Some information
		<br>
		<!-- An HTML Style Comment -->
		<?  // Denotes the start of PHP processing
        		echo "The Date and Time is: ";  // print a string, end with a semicolon
        		$mydata = "October 5, 2009"; // Assign a variable 
        		echo $mydata; // print the string variable
		?> 
        </body>
</html>
		
Example 2

As you can see in the above example, PHP code can go right within the HTML. The <? indicates the start of PHP code and the ?> denotes the end.

Take note of the different comment styles. The "//" style within PHP and "<--" outside of PHP (normal HTML)

Variables in PHP begin with "$".

"echo" is the print function.

As with JavaScript ";" ends statements.

PHP files are typically saved with ".php" not ".html"



Let's make a PHP file that outputs "Hello World!"
		<?
		
		echo("Hello World!\n");
		
		?>
		
As you can see, PHP is very similar to many other languages. There are a bunch of built-in functions (such as echo) and arguments are passed into functions through paranthesis. Strings are put into single or double quotes and the newline char is the \n. Lines of code are ended with semi-colons.

To execute this application, save it as something.php and upload it to a folder in the public_html directory of a server (itp.nyu.edu is probably a good place).

You can execute it browsing to it: http://itp.nyu.edu/~yournetid/foldername/something.php

More Information:
  • PHP: Basic Syntax - Manual


  • Variables

    Variables in PHP are not strictly typed, meaning that you do not have to differentiate between strings, integers and so on. They start with a "$".

    		<?PHP
    			$myString = "hello world\n";
    			echo($myString);
    			$myInteger = 1003;
    			echo($myInteger . "\n");
    			$somethingelse = false;
    			echo($somethingelse . "\n");
    		?>
    		
    More Information:
  • PHP: Types - Manual
  • PHP: Variables - Manual
  • PHP: Constants - Manual


  • Mathematical Operators

    		<?PHP
    			$aValue = 0;
    			$aValue++;
    			echo("aValue now = " . $aValue . "\n");
    			$aValue = $aValue + $aValue;
    			echo("aValue now = " . $aValue . "\n");
    			// % + - * / ++ -- and so on, same as in Processing/Java
    		?>
    		
    More Information:
  • PHP: Expressions - Manual
  • PHP: Operators - Manual


  • Control Structures, Logical Operators and Loops

    		<?PHP
    		
    			// If Statement
    			$aValue = 0;
    			if ($aValue == 0)
    			{
    				echo("aValue is 0");
    			}
    			else if ($aValue == 1)
    			{
    				echo("aValue is 1");
    			}
    			else if ($aValue >= 2)
    			{
    				echo("aValue is greater than or equal to 2");
    			}
    			else
    			{
    				echo("aValue something else");
    			}
    			echo("\n");
    			// Other Logical Operators ==, >, <, >=, <=, ||, &&
    
    		
    			// For loop
    			for ($i = 0; $i < 10; $i++)
    			{
    				echo("\$i = $i\n");
    			}
    			
    			// Also While
    		?>
    		
    More Information:
  • PHP: Control Structures - Manual


  • Arrays and Loops

    		<?PHP
    			// Pretty normal array
    			$anArray = array();
    			$anArray[0] = "Something";
    			$anArray[1] = "Something Else";
    			for ($i = 0; $i < sizeof($anArray); $i++)
    			{
    				echo($anArray[$i] . "\n");
    			}
    			
    			// Key Value Map
    			$anotherA = array("somekey" => "somevalue", "someotherkey" => "someothervalue");
    			$keys = array_keys($anotherA);
    			$values = array_values($anotherA);
    			for ($i = 0; $i < sizeof($keys); $i++)
    			{
    				echo($keys[$i] . " = " . $values[$i] . "\n");
    			}
    		?>
    		
    More Information:
  • PHP: Arrays - Manual


  • Functions

    		<?PHP
    			
    			function myFunction($somearg)
    			{
    				// You would do something here
    				return "You passed in $somearg";
    			}
    			
    			$passing_in = "Hello World";
    			$return_value = myFunction($passing_in);
    			echo($return_value);
    			
    			echo("\n");
    		?>
    		
    More Information:
  • PHP: Functions - Manual


  • Classes and Objects

    		<?PHP
    			class MyClass
    			{
    				var $myClassVar;
    
    				function set_var($new_var)
    				{
    						$this->myClassVar = $new_var;
    				}
    
    				function get_var()
    				{
    						return $this->myClassVar;
    				}
    			}
    	
    			$aClass = new MyClass;
    			$aClass->set_var("something");
    			echo("Var: " . $aClass->get_var() . "\n");		
    		?>
    		
    Classes and Objects in PHP are very similar to Java/Processing. Syntactically though they don't use the "." operator, instead using "->". Also, in the class definition you need to use the "this" keyword.

    More Information:
  • PHP: Classes and Objects - Manual


  • Some Built-in Functions

    isset()
    		<?PHP
    			$somevar = NULL;
    			if (isset($somevar))
    			{
    				echo("somevar is set");	
    			}
    			else
    			{
    				echo("somevar is NOT set");
    			}
    		?>
    		


    More Information:
  • Tons More Here: PHP: Function Reference - Manual


  • PHP can be used to do a myriad of tasks on the server. It can handle anything from providing a login page to searching a database to processing a form to grabbing data from another server.

    Form Handling

    A simple form in HTML:
    	<form name="myform" method="GET" action="process_form.php">
    		Name: <input type="text" name="name" /><br />
    		Comment: <textarea name="comment" cols="50" rows="10"></textarea><br />
    		<input type="submit" name="submit" value="Submit Comment" />
    	</form>
    
    This HTML snippet allows people to leave their name and a comment. You'll notice that in the "form" tag their is an "action" which is set to "process_form.php". This is the PHP script that will be sent the information when the user hits the submit button.

    process_form.php:
    	<?
    	// If both name and comment were filled out
    	if (isset($_GET['name']) && isset($_GET['comment']))
    	{
    		// Do something with the data..
    		
    		// In this case, let's write the information to a file
    		$filehandle = fopen("comments.txt",'a');
    		fwrite($filehandle,$_GET['name'] . ":" . $_GET['comment'] . "\n");
    		fclose($filehandle);
    		
    		echo("Thanks!");
    	}
    	else
    	{
    		echo("Please fill out the form");
    	}
    	?>
    
    Now that we have created a way to save the comments to a text file on the server, we can use that same text file to display the comments:

    display_comments.php:
    	<html>
    		<head><title>Comments</title></head>
    		<body>
    			<?
    				$filehandle = fopen("comments.txt",'r');
    				$contents = fread($filehandle,filesize("comments.txt"));
    				$contents_array = explode("\n",$contents);
    				for ($i = 0; $i < sizeof($contents_array); $i++)
    				{
    					echo($contents_array . "<br />");	
    				}
    			?>
    		</body>
    	</html>
    

    Interacting with JavaScript

    PHP and JavaScript, because they execute in different places (server side vs. client side) can't really interact with each-other very easily. One thing that you can do though, is use PHP to actually write JavaScript code that will be delivered to the client. Here is an example of PHP writing out what JavaScript will interpret as the value of a variable:
    	<?
    		$phpvar = "helloooooooo";  // This would come from somewhere-else presumably..
    	?>
    	<html>
    		<head>
    			<script type="text/javascript">
    				var javascriptvar = "<?=$phpvar?>";
    				alert(javascriptvar);
    			</script>
    		</head>
    		....
    
    In the above example, we set $phpvar to be something and when we write out the page in HTML we pass that variable to a variable in JavaScript so we can use it there. You'll notice the <?= .. ?> shorthand. That simply is a shortcut for: <? echo($...); ?>

    Utilizing External Data

    One powerful thing with PHP is that we are not limited to a security sandbox as we are in JavaScript. This means that we can use PHP to get data from other sources aside from the server that we are working with. There are a myriad of ways to go about this but for now the easiest will be to use file_get_contents. That built-in function allows us to either pass in a path to a file or a URL:

    Yahoo! has a nice API for accessing an RSS feed of weather data. Since RSS is a form of XML that is more "semantic" than straight HTML it gives us an easier route to working with than scraping straight HTML.

    Here is an example: http://itp.nyu.edu/~sve204/icmw_fall2009/weather.php

    <?
            $weather_data = file_get_contents("http://weather.yahooapis.com/forecastrss?p=11201");
            //echo($weather_data);
    
            $stringStart = "temp=\"";
            $stringEnd = "\" ";
    
            $startPos = strpos($weather_data,$stringStart);
            $startPos += strlen($stringStart);
            $endPos = strpos($weather_data,$stringEnd,$startPos);
            $tempString = substr($weather_data,$startPos,$endPos-$startPos);
            echo($tempString);
    ?>
    
    Essentially what the code does is searches through the string which contains the RSS source code of http://weather.yahooapis.com/forecastrss?p=11201 returned by file_get_contents and uses strpos to find the temperature portion. It then uses substr to grab that particular portion out.

    Several of the functions used in the above example are probably new to you. It is best to look them up in the String Reference portion of PHP.net

    Below is an example that gets multiple headlines from Google News:

            $news_data = file_get_contents("http://news.google.com/news?pz=1&ned=us&hl=en&output=rss");
    
            $stringStart = "<title>";
            $stringEnd = "</title>";
            
            $num_headlines = 5;
            $headlines_array = array();
            $last_pos = 0;
            
            for ($i = 0; $i < $num_headlines; $i++)
            {
    			$startPos = strpos($news_data,$stringStart,$last_pos);
    			$startPos += strlen($stringStart);
    			$endPos = strpos($news_data,$stringEnd,$startPos);
    			$last_pos = $endPos;
    			$headlineString = substr($news_data,$startPos,$endPos-$startPos);
    			$num_headlines[$i] = $headlineString;
    			echo($headlineString . "<br />");
            }   
    
    The code is almost exactly the same as the weather example but it is happening in a loop to get more than a single headline at a time.

    As you can see, this chunck of code could be made more generic.. Wouldn't it be nice to make it a function?