Working With Text Files in PHP - File Writing in Action
(Page 4 of 5 )
Let's create an example that will grab the name, sex and age of someone from a HTML form and write them to a file. There will be 2 pages in our example: getdata.php and savedata.php.
Here's the code for getdata.php:
<html>
<head>
<title> Personal Organizer </title>
</head>
<body bgcolor="#ffffff">
<form action="savedata.php" method="post">
First Name: <input type="text" name="first_name" size="30"><br>
Last Name: <input type="text" name="last_name" size="30"><br>
Age: <input type="text" name="age" size="2"><br>
Sex: <input type="radio" name="sex" value="M"> Male <input type="radio" name="sex"
value="F"> Female<br><br>
<input type="submit" value="Save Data >>">
</form>
</body>
</html> Nothing fancy here. Just a simple HTML form that posts data to a file called savedata.php. The output from the HTML above looks like this:
The savedata.php file will grab these values and save them into a file called organizer.data. Note that I will not be implementing any error checking on the form values -- only on the file operations.
Here's savedata.php:
<?php
$fName = @$_POST["first_name"];
$lName = @$_POST["last_name"];
$age = is_numeric(@$_POST["age"]) ? $_POST["age"] : 0;
$sex = @$_POST["sex"] == "" ? "M" : $_POST["sex"];
// Set the string to be written to the file
$values = "Name: $fName $lName\r\n";
$values .= "Age: $age\r\n";
$values .= "Sex: $sex\r\n";
// Open the file for truncated writing
$fp = @fopen("organizer.data", "w") or die("Couldn't open organizer.data for writing!");
$numBytes = @fwrite($fp, $values) or die("Couldn't write values to file!");
@fclose($fp);
echo "Wrote $numBytes bytes to organizer.data successfully!";
?> As you can see, I've used our fopen, fwrite and fclose functions with some @ symbols to stop PHP spitting any errors if they occur. If errors do occur, then the die() function will be called and a message output before the script terminates. Alternatively, you could've added
error_reporting(E_NONE); ... to the top of the file to stop any type of error being displayed. Our file, organizer.data now looks like this:

Next: Conclusion >>
More PHP Articles
More By Mitchell Harper