Now it's time for us to learn how to use PHP's file API to create, edit, and destroy files through PHP.
"One of the most basic things you can do with any programming language is create and manipulate data structures. These structures may be transient - in-memory variables like arrays or objects - or more permanent - disk-based entities like files or database tables; however, the ability to create, modify and erase them in a convenient and consistent manner is of paramount importance to any programmer.
Like all widely used programming languages, PHP has the very useful ability to read data from, and write data to, files on the system. But the language doesn't just stop there - PHP comes with a full-featured file-and-directory-manipulation API that allows you (among other things) to view and modify file attributes, read and list directory contents, alter file permissions, retrieve file contents into a variety of native data structures, and search for files based on specific patterns. This file manipulation API is both powerful and flexible - two characteristics that will endear it to any developer who's ever had to work with file manipulation commands." -Melonfire
fread
Start by making a file in the same folder as your php scripts. Name the file "file.txt" and write something in it like:
If you can read this my script works!
Or maybe it doesn't...
That's it!
The computer is just guessing what is in the file...(Note: It is important that you type at least 4 lines worth of text.)
Then close the file and make a new file named "fileopen.php" and type this into it:
<?php
// Store the file name in a string.
$filename = "file.txt";
// Open the file.
$filehandle = fopen($filename, "r");
// Read the files contents.
$contents = fread($filehandle, filesize($filename));
// Close file.
fclose($filehandle);
// Echo the files contents
echo $contents;
?>When you run the script you will see a blank screen with the text "If you can read this my script works!" on it. If you get an error double check your code and make sure that "file.txt" and "fileopen.php" are in the same place.
Now to explain what the script does:
<?php
// Store the file name in a string.
$filename = "file.txt";
?><?php
// Open the file.
$filehandle = fopen($filename, "r");
?><?php
// Read the files contents.
$contents = fread($filehandle, filesize($filename));
?><?php
// Read the files contents.
$contents = fread($filehandle, 4068);
?>However I find it easier to just tell the script to get as many bytes as there are:
<?php
filesize($filename)
?><?php
// Close file.
fclose($filehandle);
// Echo the files contents
echo $contents;
?>readfile
The simplest way to read a file into php and output it to the screen is to use the readfile() function.
<?php
// Store the file name in a string.
$filename = "file.txt";
// Prints the files contents.
readfile($filename);
?>fgets
Here is another way to open a file and get the contents. "fgets" gets one line out of the file specified by the file handle.
<?php
// Store the file name in a string.
$filename = "file.txt";
// Open the file.
$filehandle = fopen($filename, "r");
// Read the file line by line into a string.
while (!feof($filehandle))
{
$contents .= fgets($filehandle);
}
// Close file.
fclose($filehandle);
// Echo the files contents
echo $contents;
?>The first part specifies the file to open and creates a "handle" for it:
<?php
// Store the file name in a string.
$filename = "file.txt";
// Open the file.
$filehandle = fopen($filename, "r");
?>Next we need to recal that lesson about loops to understand the "while" loop:
<?php
// Read the file line by line into a string.
while (!feof($$filehandle))
{
$contents .= fgets($fh);
}
?>While it is not the END OF THE FILE (feof: FILE END OF) {
Get a line out of the file and add it to the string $contents.
($contents .= fgets($fh))
}<?php
$contents = fgets($fh);
?>File
Last I want to show you how to read a file into an array! If you haven't read the lesson on arrays you need to do so now! (I also recommend that you open "file.txt" and change the text because it is getting old....)
<?php
// Store the file name in a string.
$filename = "file.txt";
// Read file into array
$contents = file($filename);
// Loop through the array and print each line to the screen.
foreach ($contents as $line)
{
echo $line;
}
?>Ok, this one is the hardest, but don't worry we'll get it down!
In English the foreach loop looks like this:
For every element/line in the array "$contents": put that element into a variable called "$line" {
Then print the value of "$line" to the screen.
}Hope this lesson helped you to understand how to read files into PHP Scripts Next lesson I will show you how to do more advanced things with files!
MODES
Here are all of the modes for the fopen() function:
mode Description
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the beginning of the file.
'w' Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'a+' Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
'x' Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.
'x+' Create and open for reading and writing; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning FALSE and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. This option is supported in PHP 4.3.2 and later, and only works for local files.
Taken from the PHP Manual
Does the file have to be in the same directory as the php script or can $filename be a path to the file along with the file?
It can be a path like "html/website/index.html" for scripts in directories below the curent php script running this code.
<?php
// Store the file name in a string.
$filename = "dir/www/file.txt";
// Read file into array
$contents = file($filename);
?>Now if you need to get the contents of a file that is in a different directory on the same level (or higher) than the directory with the php script you would use the Unix statement "../" before your file path. Let me demonstrate. lets say the php file script is in "dir1" but we want to read a text file in "Subdirofdir2":
>website
>>dir1 <-PHP Script
>>>Subdirofdir1
>>dir2
>>>Subdirofdir2 <-Text FileWe can't use the path "dir2/subdirofdir2/text.txt" because there is no path like that in the current php script's directory. (the php script is in "dir1" remember). However if we could get to the "website" directory (which is the root) we could then use the "dir2/subdirofdir2/text.txt" path and it would work. So if we add the unix "../" before the path php will look for the path in the directory 1 above the current directory path (which is "website").
So our path from the php script to the text file should be:
<?php
// Go up one level - then look for the "dir2" directory.
$filename = "../dir2/subdirofdir2/text.txt";
// Read file into array
$contents = file($filename);
?>Hi,
Is there a way to get it to read from a specific string in the file, to another specific string, for example, if I wanted to get the code out of an html file, from to and assign it to $first?
Thanks!
At the beginning of the tutorial (which is great, even if from php.net. Will be going there) It says;
(Note: It is important that you type at least 4 lines worth of text.)
Why? Is this because of the file size you're referring to being 4068? So would on line be: 1017? Or is that just a co-incidence?
I only said to type 4 lines so you would have enough lines to see what is going on. You could just type 1 - but that would only leave you with a 1 line example.