Home arrow PHP arrow Page 4 - Reading, Writing and Creating Files in PHP

Reading from Files - PHP

Reading and writing to files can be useful if you do not require the storing of important data, such as a web counter. I must warn you though, that this method of storage should not be used to store passwords and other critical information, as it is not safe. Here we will discuss how to handle files and directories in PHP, specifically, how to create, read and write them.

TABLE OF CONTENTS:
  1. Reading, Writing and Creating Files in PHP
  2. File Permissions in a Unix Environment
  3. Writing to Files
  4. Reading from Files
By: Jacques Noah
Rating: starstarstarstarstar / 42
August 23, 2006

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

In PHP, to read from a file is easier than to write to a file. Instead of creating a file pointer and using the fopen() function, you simply read the entire file into an array and then retrieve it from there:

$theArray = file('theFilename');

The file() function does all the work of reading the entire file and placing it in a array. Each element in the array will then contain one line from the file.

To demonstrate how to read from a file, let's read the names from the text file that we stored them in. Create a PHP document and call it readnames.php:

 <?
$thenames = file('names.txt');
$num_names = count($thenames);
for($i=0; $i < $num_names; $i++){
echo $thenames[$i]. "<br>";
}
?>

The for Loop runs through the contents of the arrays and prints the names out. Below is a screen shot of the results I got:

Conclusion

We're finished with part one of this discussion. In part two of this article, we will be looking at file uploading and how to handle file uploads. Till then, have fun reading and writing from files.



 
 
>>> More PHP Articles          >>> More By Jacques Noah
 

blog comments powered by Disqus
   

PHP ARTICLES

- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 11 - Follow our Sitemap

Dev Shed Tutorial Topics: