PHP

A quick introduction to PHP.

1 Background

2 Language Basics

<html>
<head>
<title>Hello</title>
</head>
<body>
<?php
print 'Hello, World!';
?>
</body>
</html>

2.1 Quotes

<html>
<head>
<title>Hello</title>
</head>
<body>
<?php
  $name = "Joe";
  print "Hello, $name";
  print 'Hello, $name';
?>
</body>
</html>

2.2 Types

2.3 Super Globals

NameValue
HTTP_REFERER If the user clicked a link to get the current page, this will contain the URL of the previous page they were at, or it will be empty if the user entered the URL directly.
HTTP_USER_AGENTThe name reported by the visitor's browser
PATH_INFOAny data passed in the URL after the script name
PHP_SELFThe name of the current script
REQUEST_METHODEither GET or POST
QUERY_STRINGIncludes everything after the question mark in a GET request
<?php
   if (isset($_SERVER['HTTP_REFERER'])) {
      print "The page you were on previously was {$_SERVER['HTTP_REFERER']}<br />";
   } else {
      print "You didn't click any links to get here<br />";
   }
?>

<a href="refer.php">Click me!</a>

2.4 Execute This

3 Functions

<?php
   function multiply($num1, $num2) {
      $total = $num1 * $num2;
      return $total;
   }

   $mynum = multiply(5, 10);
?>

3.1 Call By Reference

<?php
   function square1($number) {
      return $number * $number;
   }

   $val = square1($val);

   function square2(&$number) {
      $number = $number * $number;
   }

   square2($val);
?>
<?php
   function &square1($number) {
      return $number * $number;
   }

   $val =& square1($val);
?>

3.2 Default Values

<?php
   function doFoo($Name = "Paul") {
      return "Foo $Name!\n";
   }

   doFoo();
   doFoo("Paul");
   doFoo("Andrew");
?>

3.3 Multiple Arguments

<?php
   function some_func($a, $b) {
      for ($i = 0; $i < func_num_args(); ++$i) {
         $param = func_get_arg($i);
         echo "Received parameter $param.\n";
      }
   }

   function some_other_func($a, $b) {
      $param = func_get_args();
      $param = join(", ", $param);
      echo "Received parameters: $param.\n";
   }

   some_func(1,2,3,4,5,6,7,8);
   some_other_func(1,2,3,4,5,6,7,8);
?>

3.4 Function Scope

<?php
   function foo() {
      $bar = "wombat";
   }

   $bar = "baz";
   foo();
   print $bar;
?>

3.5 Functions are Objects

<?php
   $func = "sqrt";
   if (is_callable($func)) {
      print $func(49);
   }
?>

4 Arrays

<?php
   $myarray = array("Apples", "Oranges", "Pears");
   $size = count($myarray);
   print_r($myarray);
   print $myarray[0];
?>

   

4.1 Associative Arrays

<?php
   $myarray = array("a"=>"Apples", "b"=>"Oranges", "c"=>"Pears");
   var_dump($myarray);
?>

4.2 Array Iteration

<?php
   for ($i = 0; $i < count($array); ++$i) {
      print $array[$i];
   }
?>

<?php
   while (list($var, $val) = each($array)) {
      print "$var is $val\n";
   }


   foreach($array as $val) {
     print $val;
   }

   foreach ($array as $key => $val) {
     print "$key = $val\n";
   }
?>

4.3 Manipulations

<?php
   $toppings1 = array("Pepperoni", "Cheese", "Anchovies", "Tomatoes");
   $toppings2 = array("Ham", "Cheese", "Peppers");
   $inttoppings = array_intersect($toppings1, $toppings2);
   $difftoppings = array_diff($toppings1, $toppings2);
   $bothtoppings = array_merge($toppings1, $toppings2);
   var_dump($inttoppings);
   var_dump($difftoppings);
   var_dump($bothtoppings);
?>

4.4 Filter

<?php
   function endswithy($value) {
      return (substr($value, -1) == 'y');
   }

   $people = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
   $withy = array_filter($people, "endswithy");
   var_dump($withy);
?>

4.5 In Array

<?php
   $needle = "Sam";
   $haystack = array("Johnny", "Timmy", "Bobby", "Sam", "Tammy", "Danny", "Joe");
   if (in_array($needle, $haystack)) {
      print "$needle is in the array!\n";
   } else {
      print "$needle is not in the array\n";
   }
?>

4.6 Sorting

<?php
   $capitalcities['England'] = 'London';
   $capitalcities['Wales'] = 'Cardiff';
   $capitalcities['Scotland'] = 'Edinburgh';
   ksort($capitalcities);
   var_dump($capitalcities);
   asort($capitalcities);
   var_dump($capitalcities);
?>

4.7 Serialize

5 Objects

<?php
class dog {
   public function bark() {
      print "Woof!\n";
   }
}

class poodle extends dog {
   public function bark() {
      print "Yip!\n";
   }
}

$poppy = new poodle;
$poppy->bark();
?>

5.1 Class Variables

class dog {
   public $Name;

   public function bark() {
      print "Woof!\n";
   }
}

$poppy->Name = "Poppy";

//not this way:
$poppy->$Name = "Poppy";

5.2 This

function bark() {
   print "{$this->Name} says Woof!\n";
}

5.3 Access Control

5.4 Constructors and Destructors

class poodle extends dog {
   public function bark() {
      print "Yip!\n";
   }
   
   public function __construct($DogName) {
      parent::__construct($DogName);
      print "Creating a poodle\n";
   }

   public function __destruct() {
     print "{$this->Name} is no more...\n";
     parent::__destruct();
   }
}

5.5 Copying an Object

<?php
   abstract class dog {
      public function __clone() {
         echo "In dog clone\n";
      }
   }

   class poodle extends dog {
      public $Name;

      public function __clone() {
         echo "In poodle clone\n";
         parent::__clone();
      }
   }

   $poppy = new poodle();
   $poppy->Name = "Poppy";

   $rover = clone $poppy;
?>

5.6 Comparisons

5.7 Static Class Variables

<?php
   class employee {
      static public $NextID = 1;
      public $ID;

      public function __construct() {
         $this->ID = self::$NextID++;
      }
   }

   $bob = new employee;
   $jan = new employee;
   $simon = new employee;

   print $bob->ID . "\n";
   print $jan->ID . "\n";
   print $simon->ID . "\n";
   print employee::$NextID . "\n";
?>

6 Forms

This form:
<form action="someform.php" method="GET">
Name: <input type="text" name="Name" value="Jim" /><br />
Password: <input type="password" name="Password" maxlength="10" /><br />
Age range: <select name="Age">
<option value="Under 16">Under 16</option>
<option value="16-30" SELECTED>16-30</option>
<option value="31-50">31-50</option>
<option value="51-80">51-80</option>
</select><br /><br />
Life story:<br /> <textarea name="Story" rows="10" cols="80">Enter your life story here</textarea><br /><br />
<input type="radio" name="FaveSport" value="Tennis"> Tennis</input>
<input type="radio" name="FaveSport" value="Cricket"> Cricket</input>
<input type="radio" name="FaveSport" value="Baseball"> Baseball</input>
<input type="radio" name="FaveSport" value="Polo"> Polo</input>
<br />
<input type="checkbox" name="Languages[]" value="PHP" CHECKED> PHP</input>
<input type="checkbox" name="Languages[]" value="CPP"> C++</input>
<input type="checkbox" name="Languages[]" value="Delphi"> Delphi</input>
<input type="checkbox" name="Languages[]" value="Java"> Java</input>
<br /><input type="submit" />
</form>
would be handled with:
<?php
   $_GET['Languages'] = implode(', ', $_GET['Languages']);
   $_GET['Story'] = str_replace("\n", "<br />", $_GET['Story']);

   print "Your name: {$_GET['Name']}<br />";
   print "Your password: {$_GET['Password']}<br />";
   print "Your age: {$_GET['Age']}<br /><br />";
   print "Your life story:<br />{$_GET['Story']}<br /><br />";
   print "Your favourite sport: {$_GET['FaveSport']}<br />";
   print "Languages you chose: {$_GET['Languages']}<br />";
?>

7 Cookies

<?php
   if (!isset($_COOKIE['Ordering'])) {
      setcookie("Ordering", $_POST['ChangeOrdering'], time() + 31536000);
   }
?>

<form method="POST" action="mbprefs.php"> Reorder messages:
<select name="ChangeOrdering">
<option value="DateAdded ASC">Oldest first
<option value="DateAdded DESC">Newest first
<option value="Title ASC">By Title, A-Z
<option value="Title DESC">By Title, Z-A
</select>
<input type="submit" value=" Save Settings ">
</form>

8 Sessions

9 MySQL

<?php
//Connect to the database
   mysql_connect("localhost", "phpuser", "alm65z");
   mysql_select_db("phpdb");

//Send a query and get resutls
   $result = mysql_query("SELECT * FROM usertable");
   $numrows = mysql_num_rows($result);
   print "There are $numrows people in usertable\n";

//Use a variable in the query, just place it in.
   $result = mysql_query(
      "SELECT ID FROM webpages WHERE Title = '$SearchCriteria';");

//Free memory
   mysql_free_result($result);

//Close connection
   mysql_close();

?>

10 Conclusion

URLs

  1. wikipedia:PHP, http://en.wikipedia.org/wiki/PHP
  2. Practical PHP Programming, http://hudzilla.org/phpwiki/index.php?title=Main_Page
  3. wikipedia:LAMP_%28software_bundle%29, http://www.wikipedia.org/wiki/LAMP_%28software_bundle%29
  4. wikipedia:List_of_PHP_libraries, http://www.wikipedia.org/wiki/List_of_PHP_libraries

This talk available at http://jmvidal.cse.sc.edu/talks/php/
Copyright © 2009 José M. Vidal . All rights reserved.

06 February 2008, 10:45AM