Writing to a File - Exercise

Contact Us or call 1-877-932-8228
Writing to a File - Exercise

Writing to a File

Duration: 10 to 15 minutes.

In this exercise you will write code to append entries to the Employees.txt.

  1. Open Files/Exercises/AddEmployee.php in your editor.
  2. Create short versions of the form variables.
  3. Write code to save the entry in Employees.txt, which is in the same directory. The steps involved are:
    1. Open Employees.txt for appending. Be sure to suppress errors.
    2. Write a condition that checks to see if the file failed to open.
    3. If it did open, write the output string to the file and close the file.


<meta charset="UTF-8">
if (array_key_exists('Submitted',$_POST))
//Create short versions of the Form Variables
	$firstName = $_POST['FirstName'];
	$lastName = $_POST['LastName'];
	$title = $_POST['Title'];
	$email = $_POST['Email'];

	$outputString = "$firstName\t$lastName\t$title\t$email\n";
//Open Employees.txt for appending
//Be sure to suppress errors
	$myFile = @fopen('Employees.txt', 'a');
//Write condition to check if file cannot be opened
	if (!$myFile)
		echo '<p><strong> We cannot open the file
				at this time. Please try again later.
		echo '<h1 align="center">Employee added</h1>';
		//Write $outputString to the file
		//Close the file
		echo '<a href="Employees.php">Employees.php</a>';

---- C O D E   O M I T T E D ----