Back

Example 2: Add a Tournament Bowler - Overwrites the text file

 


This is an example of using file_put_contents() to create a file containing a single string. Useful for simple data structures. Newly submitted data will replace any existing data in the text file. Commonly used with file_get_contents() for displaying and parsing simple strings. Not useful when working with complex data structures.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Working with Text Files Example 1</title>
<link rel="stylesheet" href="../php_styles.css" type="text/css" />
</head>

<body>
<div align="center">
<h3>Add a Tournament Bowler</h3>
<form action="script.php" method="get">
<label>First Name </label><input type="text" name="fname"  />&nbsp;<label>Last Name</label><input type="text" name="lname" />
<input type="submit" name="submit" value="Add" />
</form>
</div>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PHP Working with Text Files Example 1</title>
<link rel="stylesheet" href="../php_styles.css" type="text/css" />
</head>

<body>
<?php
if (empty($_GET['lname']) || empty($_GET['fname'])) {
    echo 
'<div align=center>Please enter your first and last name. Click <a href="javascript: history.go(-1)">here</a> to return to the form.</div>';
} else {
    
$bowler $_GET['lname'] . ", " $_GET['fname'] . "\n";
    
$bowlers"bowlers.txt";
    if (
file_put_contents($bowlers$bowler) > 0) {
        echo 
'<div align=center><p>' $bowler ' has been added.</p>';
        echo 
'<p>Click <a href="http://php.skillbuilderblocks.com/tutorials/unit05/ex02/form.php" target="unit05content">here</a> to return to the form.</div></p>';
    } else {
        echo 
'<div align=center><p>No data was written to the file. Click <a href="javascript: history.go(-1)">here</a> to return to the form.</div>';
    }
}
?>
</body>
</html>
kaexylqkae, kaexylqkae