PHP

CS418 - Web Programming - Spring 2015

Old Dominion University

Mat Kelly (mkelly@cs.odu.edu)
http://www.cs.odu.edu/~mkelly/cs418

What is PHP?

  • PHP: Hypertext Processor
  • Server-side scripting
  • Free alternative to Microsoft ASP
  • Can be embedded in HTML
  • Similar syntax to Perl & C
  • Frequently combined with MySQL

Basic syntax

  • Start PHP code blocks with <?php
  • End PHP code blocks with ?>
  • End lines with a ;
  • Comments (like C):
    • Single line: // This is a comment
    • Multi-line: /* ... */
  • Write output with echo "Hello world!";
  • Indicate variables with $variableName

Simple Example

<html>
 <head><title>PHP Test</title></head>
 <body>
 <?php 
    echo '

Hello World!

'; ?> </body> </html>

PHPInfo

  • The phpinfo() function displays information about your configuration, predefined variables, and other useful information
<html>
 <head><title>PHP Test</title></head>
 <body>
 <?php 
    phpinfo(); 
 ?>
 </body>
</html>
See executed output

System-provided variables

  • $_SERVER provides environment information
<html>
 <head><title>Browser Check</title></head>
 <body>
 <?php 
    echo $_SERVER['HTTP_USER_AGENT']; 
 ?>
 </body>
</html>
See executed output

Strings

  • Concatenate with "." operator
$myString = "Hello World!";
$anotherString = "42";
echo $myString . " Q " . $anotherString;
  • Output: Hello World! Q 42
$two = "2";
$three = "3";
echo $two . $three;
  • Output: 23
$two = 2; // Notice: not a string
$three = "3"; // Added to a string
echo $two + $three;
  • Output: 5

Useful String Functions

$msg = "Hello World!"; 
echo strlen($msg)."X".strpos($str,"Wo");
  • Output: 12X6

Reference the Docs

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
haystack
The string to search in.

needle
If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

offset
If specified, search will start this number of characters counted from the beginning of the string. Unlike strrpos() and strripos(), the offset cannot be negative.
  • Parameters in [] are optional

Other syntax

  • Comparison:
    ==, !=, >, >=, <, <= 
  • Assignment:
    =, +=, *=, -=, etc.
  • Logical:
    &&, ||, !
  • Conditional:
    if(condition){
        statements;
    } elseif {
        statements;
    } else {
        statements;
    }
    

PHP and Forms

Enter your name:
Hello, <?php echo $_POST["nameEntered"]; ?>!

Sanitizing Input

XKCD comic Image from http://xkcd.com/327/

Sanitization in PHP

HTTP Request Variables

  • $_GET - variables when method is GET
    • Variables are in the query string
  • $_POST - variables when method is POST (previous example)
    • Form data is not present in the query string
    • Frequently used when passing credentials
  • $_COOKIE - values stored in the browser's cookies for the page
  • $_REQUEST - associative array of $_GET, $_POST, and $_COOKIE

Arrays

  • Creation
    $names = array("John","Mike","Steve");
  • Numerically indexed
    $names[0] = "John";
    $names[1] = "Mike";
    $names[2] = "Steve";
    
  • Arbitrary indexes allowed
    $names[5] = "Bob";

Observing Arrays

  • Simple echo does not suffice
    $names = array("John","Mike","Steve");
    $names[5] = "Bob";
    echo $names
  • Output:
  • Array
  • Instead:
  • print_r($names);
    Array ( [0] => John [1] => Mike [2] => Steve [5] => Bob )

Associative Arrays

  • Define as key-value pairs
    $scores = array(
    	"Oregon" => 20,
    	"Ohio State" => 42
    );
  • Reading values
    echo $scores["Ohio State"];
  • Output
    42

Mixing Keys

  • Mixing keys
    $ary = array(
    	"John",
    	"Mike",
    	5 => "Steve",
    	"Bob",
    	"who" => "Alice"
    );
    print_r($ary);
  • Output
    Array ( [0] => John [1] => Mike [5] => Steve [6] => Bob [who] => Alice )

Looping

while(condition){
	//statements
}
do {
	//statements
}while(condition);
for(initialization; condition; increment){
	//statements
}
foreach(array as value){
	//statements
}
foreach(array as key => value){
	//statements
}

Functions

  • The PHP core has over 1800 built-in functions!
    $functions = get_defined_functions();
    echo count($functions['internal']);
  • ...but you will likely still need to write your own.
    function functionName(){
       //statements
    }						
    

Function Examples

function sayHello(){
   echo "Hello."
}
function say($something){
   echo "The function says, \"".$something."\"";
}
function whoWon($osuScore, $oregonScore){
   if($osuScore > $oregonScore){ echo "OSU Won!";}
   else { echo "Oregon Won!";}
}

PHP has OOP, OMG

class Person {                                          
    function __construct($name){
      $this->name = $name;
    }
    function whatDoYouDo(){
      echo $this->name." dances!";
    }
}

class Programmer extends Person {
    function startCoding($language){
      echo $this->name." is coding in ".$language."!";
    }
    function whatDoYouDo(){
      echo $this->name." codes!";
    }
}
$mary = new Person("Mary");
$mary->whatDoYouDo();
$john = new Programmer("John");
$john->whatDoYouDo();
$john->startCoding("PHP");
Mary dances!John codes!John is coding in PHP!