Quick Reference Guides
47 PHP Reference
Here are some quick reference reminders about PHP. This textbook is just designed to give you a toehold in how to use PHP for server-side web app programming. Once you understand how the language works, you can get more details elsewhere. One good place for tutorial-style basic PHP (including language references) is w3schools.
Quick Facts
- PHP is dynamically typed (no need to declare variable types).
- PHP is weakly typed (values of the “wrong” type are converted to a usable type, sometimes with unpredictable results).
- PHP programs run on the server side of the client-server interface. The server runs them to help write HTTP Responses.
- PHP programs get input from HTTP Request parameters.
- PHP programs write text output into the HTTP Response Body. This text can be HTML, CSS and/or JavaScript code, or it can be a JSON encoded string of data.
- AJAX allows the client to send HTTP Requests from a JavaScript program, receive the HTTP Response without triggering a page reload, and incorporate the new information into the page using DOM Manipulation.
- PHP programs must manage session state themselves
Web App Security
PHP programs must use security best practices to protect code, data and users
- Validate and sanitize user input using filter_input().
- Use SQL prepared statement parameters.
- Hide sensitive information on the device, in transmission, and on the server.
- Use hashing and salting to store passwords.
- Never store passwords or other sensitive information in the $_SESSION object.
PHP Tags
<?php … ?> is the script tag, <?= … ?> is the expression tag
Output
echo "<p>Hi</p>";
Debugging Output
var_dump($a);
Variables
$x = 5;
Start with a $ character, dynamically typed, no declaration is necessary.)
Global or function scope only. No block-level scope.
Types
PHP supports values of type int, float, bool, null, string, array, and object.
vardump($x); // echoes the type and value of $x PHP supports c-style casting for type conversion.
$x = (int)$x; // converts $x to int $x = (float)$x; // converts $x to float
Arrays
Arrays are highly flexible and can mix integer and associative key values. Array literals are enclosed in square brackets.
$a=[]; a[0]="first item"; a[1] = "2nd item"; array_push($a, "3rd item"); $a=["first item", "second item", "third item"];
$user=[]; $user["studentid"]="84390283"; $user["age"]=23;
$user = ["studentid" => “84390283", "age" => 23];
Strings
Use single quotes for raw strings, double quotes to embed variables:
echo "Hello $name"; // embeds variable $name echo "Hello $row[name]"; // embeds $row["name"] echo 'Hello $name"; // prints "$name" into output
Functions
function spam($a, $b=0, $c=0) { return $a + $b + $c; }
Control Structures
Here are the main PHP control structures used in this book. This list is not exhaustive.
if (boolean) { // do something } elseif { // do something else } else { // do a default thing } while (boolean) { // do something } do { // do something } while (boolean); for (initialize; test; change) { // do something } foreach ($a as $k => $v) { // $k and $v are the key and // value of associative array $a }
Operators
PHP supports all the arithmetic and Boolean operators you learned in your first programming course. But watch out for automatic type conversion (weak typing). Here are some examples:
- 35 + ” dollars” is 0, not “35 dollars”
- “” == false is true
String concatenation uses the dot (.) operator.
To help get around automatic type conversion, PHP also supports === (true if the type and value match) and !== (true if either the type or the value do not match).
The logical AND, OR, and NOT operators are &&, ||, and ! respectively, but you can also use and and or.
Classes
A class is a blueprint for creating objects. It contains instance variables and methods (functions). You can use a constructor method to set up instance variables when the object is created.
class Person { // instance variables (optional) public $name = ""; public $age = -1; // constructor is named __construct (two underscores) // $this->name references the name variable function __construct($name, $age = -1) { $this->name = $name; $this->age = $age; } // method to increase the $age instance variable function increase_age($increment) { $this->age += $increment; } }
Objects
New objects are created from a class using the new keyword.
$p1 = new Person("Sam"); $p2 = new Person("Anne", 30);
Use the arrow (->) operator to access instance variables and methods.
$p1->increase_age(11);
echo "Your name is $p1->name.";
Parameters (Client)
Parameters can be sent from input elements enclosed in a form element:
<form action="some_file.php" method="method"> <!-- named input elements go here --> <input type="hidden" name="parameter name" value="value to send"> <input type="submit"> </form>
The method attribute can be GET or POST.
Input Elements:
- Input elements require a name attribute in order to send a parameter.
- Input elements with the required attribute must be filled in before the browser will allow the form to submit.
- Input elements with attributes such as min, max, step, size, etc. will also be checked by the browser before submission.
- Input elements with type=”hidden” can be used as a form of primitive session management, with values written by a PHP program.
- See HTML Reference for a bigger list of input types and attributes.
JavaScript Form Validation:
- The submit event attaches to a form element. The listener for the event will be called before the form is submitted.
- The event.preventDefault() method will prevent the form from being submitted.
Parameters (Server)
filter_input(INPUT TYPE, "param", FILTER) INPUT_GET, INPUT_POST FILTER_VALIDATE_INT, FILTER_VALIDATE_FLOAT, FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_URL, FILTER_SANITIZE_SPECIAL_CHARS
AJAX (Client)
To get HTTP Response body text:
fetch(url) .then(response => response.text()) .then(success)
To get objects or values by decoding the JSON text in HTTP Response body:
fetch(url) .then(response => response.json()) .then(success)
GET parameters can be appended to the url (e.g. “url?x=5&y=3&z=hi”)
AJAX (Server)
<?php // receive params, retrieve data, etc. // construct a $data array or object to send back to client echo json_encode($data);
Session Management
session_start() $_SESSION[key] isset($_SESSION[key]) session_destroy()
Password Hashing
$hash = password_hash($user_pwd, PASSWORD_DEFAULT) password_verify($user_pwd, $hash)
Some Useful Global Functions
Array Functions
count($a) array_push($a, $item)
String Functions
strlen($s)
Number Functions
number_format($n, $p) // rounds $n to $p decimal places rand($min, $max)
Date Function
date($format)
Debugging Functions
var_dump($var) phpversion()
PHP Data Objects (PDO)
See SQL/PDO Reference.