NSWI142: Web Applications

4. PHP Introduction

Jáchym Bártík, KSI
jachym.bartik@matfyz.cuni.cz

Preliminaries

Please read this section at least one day prior to the seminar. This section outlines what you are expected to know, be able to do, or prepare in advance. Following these instructions will help you get the most out of the seminar and ensure smooth participation.

Preliminaries

Before the start of the practical, you should be able to:

  • Explain <?php opening tag and why we need it.
  • Write hello world in PHP.
  • Create an array and iterate the array using foreach in PHP.
  • Create a nested array with combination of number and string keys in PHP.

You can use OneCompiler PHP to test yourself before the lecture.

Please refer to PHP array documentation for more details on arrays.

Preliminaries software

This slide applies to you only if you plan to use your own computer for the practical.

Before the start of the practical, make sure that:

  • You have PHP installed.
  • You can run php commands from command line.

Cheatsheet: How to run PHP

Be careful which PHP version you are running - you want at least version 8. Older versions may lack some features. Check Supported Versions.

  • Use one of many online compilers, e.g. [1], [2], [3].
  • Use PHP from a command line by running php file.php. You can:
    • use our Webik server via SSH
    • install it on your own
    • use a Docker image
  • Use a web server with PHP support.
    • On Webik, upload PHP file into public_html directory and open
      webik.ms.mff.cuni.cz/~<username>/file.php.
    • Install XAMPP / MAMP / LAMP / WAMP on your own computer.
    • Use built-in server by running php -S localhost:8080 from your project directory.

Cheatsheet: PHP: Hypertext Preprocessor

Input:


This text is sent <strong>a⁠s is</strong> without any modifications.
<?php
  // We are inside PHP script that is executed by PHP preprocessor
  echo 'The time is ' . date('H:i:s');
?>

Again, this text is sent a⁠s is.
    

Output:


This text is sent as is without any modifications.
The time is 04:20:00
Again, this text is sent as is.
    

Cheatsheet: PHP Variables and types


<?php

$age = 42;
$message = "Your age is $age"; // double quotes interpolate, single quotes do not
$fullMessage = $message . "\nWelcome."; // concatenation uses .

echo($message);
echo $message; // echo is actually language construct, so you can write it without parentheses

var_dump($fullMessage); // dump (print) any variable

$age = 'John Doe'; // dynamically typed language: variable can change its type

$pi = 3.14; // float
$isAdult = true; // boolean
$nothing = null; // null

$userProvidedName = 'John <img src="pepe_hacker.png"> Doe';
// escape dangerous strings before outputting them to HTML
echo 'Hello user ' . htmlspecialchars($userProvidedName);
// Hello user John &lt;img src="pepe_hacker.png"&gt Doe
    

Cheatsheet: Control Structures


<?php

if ($name === 'John') {
  ...
} else {
  ...
}

while ($x >= 0) {
  ...
}

do {
  ...
} while (strlen($text) > 0)

for ($i = 0; $i < 3; $i++) {
  ...
}
    

Cheatsheet: Arrays


<?php

$food = [ 'apple', 'tomato', 'pear' ]; // indexed
$user = [ 'name' => 'Joe', 'id' => 42 ]; // associative (like Python dict)
$empty = [];

// Access
$food[0]; // 'apple'
$user['name']; // 'Joe'

$food[] = 'banana'; // append
$last = array_pop($food); // pop from end

// Existence checks
isset($user['name']); // true if key exists and not null
array_key_exists('name', $user); // true even if null

// Looping through array
foreach ($array as $value) { echo $value } // $value is a copy
foreach ($array as &$value) { $value *= 2; } // & mutates original
foreach ($array as $key => $value) { echo "$key: $value\n" }
    

Cheatsheet: Working with JSON


<?php

$data = [ 'name' => 'Joe', 'skills' => [ 'math', 'code' ], 'id' => 42 ];

// Encode: returns JSON string
$json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
echo $json;

// Decode to an associative array (similar to a Python dictionary)
$array = json_decode($json, true); // true => associative array
$array['name'];
    

<?php

file_put_contents('data.json', $stringData); // write string to file
$content = file_get_contents('data.json'); // read string from file

// You can append to the file and obtain an exclusive lock to prevent concurrency issues
file_put_contents('data.json', $stringData, FILE_APPEND | LOCK_EX);
    

Where to find documentation?

The official PHP documentation is available at php.net/docs.php.

Examples:

Comparisons in PHP

Prefer strict comparisons (===, !==) to avoid unexpected type conversion.

Only use loose comparisons (==, !=) when you need it.


<?php

42 == '42'; // true (type conversion)
42 === '42'; // false (different types)

$var = 0;
$var == false; // true (type conversion)
!$var; // (not operator applied to zero) true (type conversion)
$var === false; // false (different types)
    

strpos(string $haystack, string $needle, int $offset = 0): int|false - Finds the position of the first occurrence of a substring in a string. Returns 0 if the substring is found at the beginning of the string, returns false if not found.

PHP Standards Recommendations

Set of standard recommendations for writing PHP code.

Check PSR-1: Basic Coding Standard and PSR-12: Extended Coding Style Guide.


<?php

methodNamesAreInCamelCase();

if ($condition) { // Spaces after if keyword, and before opening brace that MUST be on the same line
    // Code MUST use an indent of 4 spaces for each indent level, and MUST NOT use tabs for indenting.
}

for ($i = 0; $i < 10; $i++) { // Note spaces around operators
    // for body
}

// You MUST NOT close the PHP tag if you do not have any intended HTML after it
    

Exercise: Rendering JSON

The objective of this exercise is to create a script that renders JSON as an HTML document.

While the topic is related to web applications, most of the functionality is not web-specific.

JSON file

Download and save JSON file with data and familiarize yourself with it.

There are two approaches to implementing this exercise.

The first one is easier.

The second one is a little more complicated but also more general.

Please select the approach based on your coding experience.

Both of them are described on the following slides.

Basic version: Rendering books

Your objective is to explore the JSON structure and render it as a list of books.

  • For each book, render its title, year of publication, publisher, author, and reviews.
  • For each review, render author and content.

See the fragment below as an example of output.


<ul>
  <li>
    <h2>The Quantum Enigma</h2>
    <p>by Dr. Emily Carter</p>
    <p>published by Future Horizons Press in 2023</p>
    <p>Reviews</p>
    <ul>
      <li>John Doe <br/> A fascinating dive into the mysteries of quantum mechanics. Highly recommended!</li>
      ...
    </ul>
  </li>
  ...
</ul>
    

Do not hardcode the values - you must load them from the JSON file.

Advanced version: Rendering JSON

Create a general rendering script.

  • An array is rendered as an unordered list of item renderings.
  • An object is rendered as an unordered list, where the content contains the key value and rendering of the value, separated by a colon (':').
  • Primitive types are rendered as strings.

The algorithm should produce the following fragment:


<ul>
  <li>
    <ul>
      <li>title: The Quantum Enigma</li>
      <li>year_of_publication: 2023</li>
      ...
      <li>reviews: <ul> ...
    </ul>
  </li>
  ...
</ul>
    

Exercise: Simple form

Objective of this exercise is to create a simple form application.

A user can fill in the form and submit it.

In the next step, the user confirms the details and submits it again.

All (final) submissions are saved using a local JSON file - do not use for production!

In addition, the user can also list all submitted data.


Warning: This is only an introductory exercise. The chosen approach is suitable for small applications at best. We will talk about better ways in the follow-up practical. For information about development and deployment of medium and larger applications, see NSWI153.

The form

Download event registration form and save it as registration.php.

Familiarize yourself with the form and with the way it submits data.

Continue to the next slide once you are done.

The form processing

Create confirm-registration.php file and explore the value of the $_GET variable.

Next, generate a summary of the submitted data and a confirmation dialog.

The dialog must use POST method to finish-registration.php.

Post the data using hidden form elements.

The objective is to allow the user to review and confirm the registration.

Continue to the next slide once you are done.

The registration

Create and implement finish-registration.php script.

The script must store the information using a JSON file.

The JSON file location should be ./database.json, relative to the finish-registration.php script file.

Continue to the next slide once you are done.

The overview

Create index.php file.

The site will serve as a landing page for the registration.

The page must contain a link to the registration.php file.

In addition, the page must contain a list of all registered participants.

For each participant, list the full name and workshops he or she registered for.

Continue to the next slide once you are done.

Bonus: Wrapping up

Make sure that all generated HTML is valid and that you are using htmlspecialchars to sanitize output.

Feel free to add graphics or text to improve the overall content or visual appearance.

Upload all your files to the ~/public_html/ai-event/ directory at Webik.

ReCodEx

New task:

  • PHP - Šablonátor (2 points, optional)

This task will be useful for your mandatory final project.

Examples of real-world template engines:

Questions, ideas, or any other feedback?

Please feel free to use the anonymous feedback form.