Part 3. PHP library

This third part is dedicated to the writing of a PHP library that we will be completed as the project progresses. For now, this library will contain three functions:

At the root of the site, create a new directory lib in which you will create a lib.php file.

Creating a key

In this project, we are not going to develop an authentication system with a username and password. Each shopping list will be accessible publicly, but will be protected by a key to prevent unscrupulous visitors... to access lists that don't belong to them. Later (in the section Creating a new list) the key will be passed in parameter in the URL of the page and will serve as a verification system. Although this principle is not totally reliable, it has the advantage of being able to be implemented quickly.

Right now, we'll just write the key generation function.

Write a function generateKey($length = 32) which returns a random key of length $length composed of :

The following syntax allows you to include the library in scripts where you want to use it:


Test your function before continuing.

Error management

For safety and ergonomic reasons, it is important to treat correctly any errors that might occur. We will redirect all error messages to the errorManager($message, $url = NULL) function. which we're going to write in the lib.php library.

The errorManager($message, $url = NULL) function:

Write and test the function.

Connection to the database

Write a dbConnect() function that will connect to the database:

Test your function before proceeding.

Creating a new list

Write a dbNewList($db, $name, $ukey = NULL) function that creates a new shopping list in table `lists'. The parameters of the function are :

Test your function before proceeding.


Complete the new.php script so that it will

If an error occurs during script execution, display an appropriate message and stop the script.

If everything is right, the script redirects the user to the generic /list/ page. with parameters we'll use later. For now, create a list at the root of the site. Create in this folder a file index.php which contains the following provisional code:

var_dump ($_GET);

Test the creation of a new list. Remember to clean the database when you're done.

See also

Last update : 11/24/2021