Czech version
logolink

< Back to the list of lessons

Generating Letters Using PHP

PHPContent of the lesson:

  • Larger Text Outputs
  • Assignment
  • Date
  • Greeting
  • Function for Generating Passwords

Larger Text Outputs

You often need to create larger text outputs like business letters for clients of insurance companies or bank offices or just a message for a group of people (students, employees etc.). Examples:

  • Business correspondence - so called mass correspondence - an institution needs to send a letter to every client and this letter contains specific information for him (usually data from a database) and relevant information. The letter can contain specific offers for the client (according to the length of partnership, used products etc.). The company can concretely offer packets of digital TV, insurance offers or can just send security information (PIN for credit card, password to account etc.).
  • Important messages - for example a new student of university should get his username and password to be able to log into the information system.

These problems can be solved using the mass correspondence function inside Office. The other way (using PHP) can be used in case we need to generate documents from different input materials, Linux text outputs, PDF files, HTML files or quality documents for LaTeX system.

We will describe a solution for a problem connected with administrating an information system - imagine that you need to send letters to employees about changing passwords to IS and you want to generate the passwords and include them inside letters. Passwords have to be generated according to required complexity for IS.

Assignment

Text of Letter

Your task is to write a script which will generate HTML page with short letters for all users from input materials. The structure will be like the following rows (information drawn in bold will change dynamically):

  1. Date: 16. 05. 2010
  2. Addressee: Jaromír Karola
  3. Dear Sir!
  4. I am writing to you to let you know about your new password for information system.
  5. Your new password for login: p0n6vbqk9c (P0N6VBQK9C)
  6. František Žebř, computer network administrator

The input materials are two arrays with users (every user has his name and sex) - these arrays have been already filled to simplify the solution (you do not have to load data from an external database).

Input arrays with data
$uzivatele = array("Jaromír Karola", "Andulka Šťastná", "Ota Menoušek", "Oto Najbrt", "Ágnes Císařová"); $uzivatelepohlavi = array("M", "Z", "M", "M", "Z");

Requirements for Properties of Password

The password will be randomly generated from suitable lower-case letters and numbers. The size should be between 10 and 15 characters and every password must be unique. You should discard characters which cause problems - think about characters which are similar to numbers and can confuse some users. Are we going to use both lower- and upper-case characters?

Structure of Script

We will process the letters for all users using a for cycle (ideal to process an array with known number of elements).

For cycle

for($k=0;$k<count($uzivatele);$k++){
  print("<p>Date: ".."</p>");
  print("<p>Addressee: ".$uzivatele[$k]."</p>");
  Greeting
  Generating password inside variable $heslo
  print("<h2>Your new password for login: ".$heslo." (".heslo velkými písmeny.")</h2>");
  print("<p>František Žebř, computer network administrator</p>");
}

We will generate the password using a new function generujheslo. It will require one parameter and return the password. The input parameter should be the requested length of password. Add this function above the previous part of script.

Function generujheslo

function generujheslo($delka){

  $heslo = "";
  $znakyhesla = "023456789bcdfghjkmnpqrstvwxyz";
}

There are two lines of code inside the function - the variable heslo where we will store the generated password and which will be returned. The second line contains a string of characters which will be used to generate the password (Why do we not use all letters and numbers?).

The basic structure of our script can be downloaded here: dopisy-zadani.txt.

Steps of Solution

Date

The current date should be written in the first line using the format day, month, year (for example 3. 6. 2011).

Look inside the documentation of function Date in PHP and add this function inside the script using proper parameters.

When reading the documentation you can find samples and answers from users under the specification of the function. In this case you can use the sample 4 to understand this function:

Sample 4 from the documentation of function Date from php.net
Example #4 date() Formatting

<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone

$today date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today date("m.d.y");                         // 03.10.01
$today date("j, n, Y");                       // 10, 3, 2001
$today date("Ymd");                           // 20010310
$today date('h-i-s, j-m-y, it is w Day');     // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today date('\i\t \i\s \t\h\e jS \d\a\y.');   // it is the 10th day.
$today date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:03:18 m is month
$today date("H:i:s");                         // 17:16:18
?>

Greeting

The solution for this part is quite simple. The greeting should be changed according to the sex of each person: Dear Sir/Dear Madam.

All you have to add is a simple condition IF - THEN which will write a proper text according to the current item's value of array $uzivatelepohlavi. Every single person is the item with index $k.

Greeting line

for($k=0;$k<count($uzivatele);$k++){

print("<p>Date: ".Date("d. m. Y")."</p>");
print("<p>Addressee: ".$uzivatele[$k]."</p>");

if ($uzivatelepohlavi[$k]=="M"){
print("<h1>Dear Sir!</h1>");
}else{
print("<h1>Dear Madam!</h1>");
}
...

Function for Generating Passwords

Solution I

Complete the script for generating a password using functions substr, mt_rand, strlen, strstr and strtoupper.

Solution II

Use and describe in details the following code:

Generating password

function generujheslo($delka){

  $heslo = "";
  $znakyhesla = "023456789bcdfghjkmnpqrstvwxyz";
  $i = 0;
  while ($i < $delka) {
    $znak = substr($znakyhesla, mt_rand(0, strlen($znakyhesla)-1), 1);
    if (!strstr($heslo, $znak)) {
      $heslo = $heslo.$znak;
      $i++;
    }
  }
  return($heslo);

}

$uzivatele = array("Jaromír Karola", "Andulka Šťastná", "Ota Menoušek", "Oto Najbrt", "Ágnes Císařová");
$uzivatelepohlavi = array("M", "Z", "M", "M", "Z");

for($k=0;$k<count($uzivatele);$k++){

   print("<p>Date: ".Date("d. m. Y")."</p>");
  print("<p>Addressee: ".$uzivatele[$k]."</p>");

   if ($uzivatelepohlavi[$k]=="M"){
    print("<h1>Dear Sir!</h1>");
  }else{
    print("<h1>Dear Madam!</h1>");
  }

   print("<p></p>");
  $heslo = generujheslo(8);

    print("<h2>Your new password for login: ".$heslo." (".heslo velkými písmeny.")</h2>");
    print("<p>František Žebř, computer network administrator</p>");

}

You can see that we do not generate unique passwords but we only check that no character is repeated inside our passwords.

Homework

  1. Adjust the script to be able to prepare an output file for LaTeX system - every letter should start at the beginning of a new page. Try to correct the typography of the letter - suggest a new function predlozky which will add non-breakable spaces before single-character prepositions and conjunctions.
  2. Adjust the script to generate unique passwords only (you can use the variable $k, insert it inside the function using the command globals and also explain this command).
  3. What if we wanted to insert the final letters from HTML to a text processor like Microsoft Word? Is it possible to adjust the letters to be displayed one per page after inserting to Microsoft Word?

Questions

  1. In which situations are computers used when creating a larger amount of messages or letters?
  2. Characterize functions in PHP, especially the commands globals, return and inserting parameters by address or by value.
  3. Characterize the functions substr, mt_rand, strlen, strstr and strtoupper.
webdesign, xhtml, css, php - Mgr. Michal Mikláš