Web Applications

PHP Introduction

Objectives

  • PHP Introduction
  • Exercise: Rectangle
  • Demonstration: Reading JSON from a file
  • Exercise: HTML form generator
  • Exercise: Dynamic HTML form generator

PHP Introduction

It is interpreted language, like Python. PHP files should utilize .php extension. You can run PHP script file using:


php ./file-to-run.php
    

PHP code section must start with:


<?php … ?>
    

There is an online documentation with examples!

You can install locally or run using an online sandbox ( onlinephp.io, onecompiler.com, ... ).
There is PHP interpreter available at lab computers.

Variables

  • variables start with $
  • string concatenation with .
  • strings in single quotes uninterpreted: 'a $b \n'
  • strings in double quotes interpreted: "a $b \n"
  • usual operations +, -, * ...



// number
$n = 3;
// boolean
$b = true;
// string
$s = 'abc';
// interpreted string, similar to f-string in Python.
$s = "Value: $n";
    

Functions

Declared using 'function' keyword.


function doWork($name, $age) {
  return 42;
}

$result = doWork('Ailish', 23);
print($result);
     

Control structures

Similar to you C-like language.


if (expression) stmt; elseif (expression) stmt2; else ...

while (expression) stmt;

do stmt; while (expression);

for (init; expression; inc) stmt;

foreach (array as [ $key => ] $value) stmt;

switch (variable) { case ... default: }

...
     

There is also "else if" and "elseif".

Array

An array in PHP is actually an ordered map. The structure is fairy versatile and can be used as an array, vector, hash table, dictionary, an more. A key to an array can be either string or an int.

Beware of key type casts! For example. string with a valid decimal int will be converted to an int.


$array = [1, 2, 3];
$array[10] = 10;
var_dump($array);

$array["10"] = "ten"; // "10" and 10 are same keys due to auto-conversion.
var_dump($array);

$person = [ "name" => "Ailish", "age" => 12];
print($person["name"]."\n");
var_dump($person);

// Check if set and exists.
var_dump(isset($person));
var_dump(isset($person["name"]));
var_dump(isset($person["nickname"]));
     

A var_dump print information about given variable. Use this to get a content of a variable for debugging purpose.

Type Conversions

PHP utilize so called type juggling, in other words automatic type conversion. This can lead to an unexpected behavior.


$number_as_string = "2";
$number = 40;

// You can see that based on the output we are not capable to
// determine the variable type.
print($number_as_string); // 2
print($number); // 40

var_dump($number_as_string + $number); // int(42)
var_dump($number_as_string . $number); // string(3) "240"

     

It is better to not rely on automatic type conversion. Be a professional know what your code is doing!

Exercise: Rectangle

Create a function that given size of a rectangle computes and prints its perimeter and area. In addition this function renders the rectangle to output using ASCII art, see example bellow. Test the functions by calling it several times and properly handle different inputs.
Mind code decomposition!
For sake of simplicity, do NOT read from standard input, hard-code values in your code!

Example output for values: 5 3

  Perimeter: 16
  Area: 15

  *---*
  |...|
  *---*
  

Make sure you properly handle edge-cases, like size 0, 1, and 2.

Demonstration: Reading JSON from a file

Employ PHP to load JSON from URL and render it to standard output. Utilize following functions:




$contentAsString = file_get_contents("path-url-here");
// https://www.php.net/manual/en/function.json-decode.php
// When is second argument true, we get an array.
$content = json_decode($contentAsString, true);
foreach ($content as $key => $value) {
  $sanitizedKey = htmlspecialchars($key);
  $sanitizedValue = htmlspecialchars($value);
  print("$sanitizedKey : $sanitizedValue \n");
}
  

Exercise: HTML form generator

The goal is to implement a simple form generator using PHP. The form is generated based on a form specification, our made up format. For now we hard-code the definition as a part of the PHP script file. You can find the definition on the next slide.

Your form must support three input types: text, number and hidden. Every input element must have a name.

The text and number input elements may have a label, and required set as well.

The number input element can have a min and max.

When generating the form, you should ignore any invalid field.

The dialog should submit data using GET method to an URL specified by action.

Page title can be specified using title.

Form specification example

Copy this into your code!


$definition = [
  "title" => "Form",
  "action" => "/nswi142/practicals/script/02-handle-form.php",
  "fields" => [
    [
      "name" => "full_name",
      "type" => "text",
      "label" => "Name",
      "required" => true,
    ],
    [
      "name" => "age",
      "type" => "number",
      "label" => "Age",
      "min" => 0,
      "max" => 1000,
    ],
    [
      "name" => "type",
      "type" => "hidden",
      "value" => "secret-code",
    ],
  ],
];
    

Output

A possible output for previous input. You have to generate valid HTML!


<!doctype html><meta charset=utf-8><title>Form</title>

<form action="/nswi142/practicals/script/02-handle-form.php" method="GET">

  <label>Name <input type="text" name="full_name" required> </label>

  <label>Age <input type="number" name="age" min="0" max="1000"> </label>

  <input type="hidden" name="type" value="secret-code">

  <input type="submit" value="Submit">

</form>
    

Exercise: Dynamic HTML form generator

The goal is to extend the previous exercise wit additional functionality.

  • Make sure you sanitize the output (htmlspecialchars).
  • Make sure you properly handle type specific properties. For example do not render min and max for type=text even when provided.
  • Load definition on every script run from JSON document .
  • Upload your solution to /public_html/04-form.php directory.

How are we doing?

  • PHP Introduction
  • Exercise: Rectangle
  • Demonstration: Reading JSON from a file
  • Exercise: HTML form generator
  • Exercise: Dynamic HTML form generator
Questions, ideas, or any other feedback?

Please feel free to use the anonymous feedback form.