Jáchym Bártík, KSI
jachym.bartik@matfyz.cuni.cz
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.
Before the start of the practical, you should be able to:
You can use OneCompiler PHP to test yourself before the lecture.
Please refer to PHP array documentation for more details on arrays.
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:
Be careful which PHP version you are running - you want at least version 8. Older versions may lack some features. Check Supported Versions.
php file.php. You can:
public_html directory and openwebik.ms.mff.cuni.cz/~<username>/file.php.php -S localhost:8080 from your project directory.Input:
This text is sent <strong>as 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 as is.
Output:
This text is sent as is without any modifications.
The time is 04:20:00
Again, this text is sent as is.
<?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 <img src="pepe_hacker.png"> Doe
<?php
if ($name === 'John') {
...
} else {
...
}
while ($x >= 0) {
...
}
do {
...
} while (strlen($text) > 0)
for ($i = 0; $i < 3; $i++) {
...
}
<?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" }
<?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);
The official PHP documentation is available at php.net/docs.php.
Examples:
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.
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
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.
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.
Your objective is to explore the JSON structure and render it as a list of books.
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.
Create a general rendering script.
':').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>
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.
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.
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.
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.
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.
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.
New task:
This task will be useful for your mandatory final project.
Examples of real-world template engines: