Photo web hosting - USING PHP TO MANAGE FILES To demonstrate the
USING PHP TO MANAGE FILES To demonstrate the file() function, let s use filetest03.txt, which contains just two lines as follows: david, codeslave chris, bigboss This will be used as the basis for a simple login system to be developed further in Chapter 9. PHP Solution 7-2: Reading a text file into an array 1. Create a PHP file called file.php inside the filesystem folder. Insert the following code (or use file01.php from the download files for this chapter):
This draws the contents of filetest03.txt into an array called $users, and then passes it to print_r() to display the contents of the array. The
tags simply make the output easier to read in a browser. 2. Save the page, and load it in a browser. You should see the output shown in the screenshot to the right. It doesn t look very exciting, but now that each line is a separate array element, you can loop through the array to process each line individually. 3. You need to use a counter to keep track of each line; a for loop is the most convenient (see The versatile for loop in Chapter 3). To find out how many times the loop should run, pass the array to the count() function to get its length. Amend the code in file.php like this (or use file02.php): $tmp[0], ‘password’ => $tmp[1]); } ?>185
If you are in need for cheap and reliable webhost to host your website, we recommend http web server services.