Comm Lab Web Week 2

Introduction to PHP

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.

PHP is interpreted on a webserver before the page is delivered to a client. 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>
		
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.

";" 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 a web accessible directory of a server.

You can execute it browsing to it: http://yourdomain/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


  • 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 " . $_GET['name']);
    	}
    	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>
    

    Query Strings: Hyperlinks with Data

    Forms aren't the only way to send data to the server. You can actually tack data onto a regular HTTP request with a query string.

    <a href="linkto.php?var1=value1&var2=value2">Link with Data</a>
    
    which ends up looking like this: Link with Data