This article is a follow up to my previous article on PHP encryption techniques. To demonstrate one-way encryption in PHP, this article describes how to start building a secure online diary application. The one-way encryption will allow the diary to log a user in and generally encrypt the contents of the file that it loads.
How It Works
First, the user has to log into the diary. This ensures that only the person that is supposed to use the diary has access to it. We will use one-way hashing to ensure password safety. The user will be presented with an HTML form that will take a password and then compare it to the stored hash algorithm.
Both the password and the diary contents will be stored in a file. Because PHP works mighty fine with MySQL, we will create some code to show how to store both pieces of information in a MySQL database as well. So you will have not only the option to store them in either the database or file, but you will also have the code to make it possible.
The Database Stuff
The diary takes two tables: the users and contents tables. The users table contains information about the users, such as their names and passwords, and the contents table contains information about the contents of the diary. To ensure that more than one person is able to start their own diary, I've created two tables: one to hold the information about a user and another to hold information about the different kinds of content that can be held by different users. Below is an outline of the tables, followed by the SQL (which you can copy and paste into your MySQL client to create them).
The users table has three fields:
idÂ Stores a unique new ID number for each new user
nameÂ Stores the name of the user
passÂ Stores the password of the user
The contents table has three fields:
cidÂ Creates and stores a unique number for each new piece of content
txtÂ Stores the main text of the diary
uidÂ Stores the name of the user who is responsible for creating the text (This field also acts as a foreign key that links to the users table.)
Below is the SQL for the database tables:
When a user has logged in, the user name and ID is put into session variables and then the user is directed to the editor script. This script shows the unencrypted contents that this user stored previously. To edit the text, the user is presented with a form element called the
textarea. There the user can move up and down, write and erase, and do lots of other things. Because the form element provides all of this functionality, we do not actually have to worry about implementing text manipulation. This makes our job extremely easy.
After the user finishes writing the day's entry in the diary, he or she then clicks on the button that says encrypt and exit. When the user presses this button, the text contained in the form element is sent to the PHP code for processing. One of the things the PHP code does is encrypt the text. Then the user is transferred to the login page.