1. Opening & Closing Files
The ability to manipulate files can be both fun and useful. The first step of the process would be to identify the file that you want to manipulate, and open it.
PHP uses the fopen() function for the purpose of opening an existing file or creating a new file if the specified file does not already exist. The function syntax is: fopen(filename, method);
It is probably obvious that "filename" refers to the name (and also the path) of the file, but method may not be quite as obvious. It refers to the type of access that is allowed each time the file is opened. The most common options are:
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. |
x+ | Create and open for reading and writing; otherwise it has the same behavior as 'x'. |
c | Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. |
c+ | Open the file for reading and writing; otherwise it has the same behavior as 'c'. |
When using fopen(), a file handle is returned which identifies the open file connection and will later be used to read/write/close the file, all very important steps. We can store that file handle in a variable. Let's look at some examples of how to open a file.
$FileHandle1 = fopen('storage.txt', 'w');
$FileHandle2 = fopen('http://www.your-website.com/', 'a+') or die("Uh-oh! Errors!");
$FileName = "directory-path-to-file/filename.php";
$FileHandle3 = fopen($FileName, 'r');
?>
So as you can see, you can mix and match your options as needed to get the job done.
The most important part of opening a file is remembering to close it when you are done editing. The fclose() function accepts one parameter, that parameter being the file handle of the open file that needs closed.
$FileHandle1 = fopen('storage.txt', 'w');
fclose($FileHandle1);
$FileHandle2 = fopen('http://www.your-website.com/', 'a+') or die("Uh-oh! Errors!");
fclose($FileHandle2);
$FileName = "/directory-path-to-file/filename.php";
$FileHandle3 = fopen($FileName, 'r');
fclose($FileHandle3);
?>
If you are getting errors when trying to open/edit/close files, it might be because PHP does not have permission to edit files on the server. You will need write permission enabled in the directory that the file is stored in.
Next up, we will learn how to read and write to files.
Summary:
Function | Description |
fopen() | Opens a File Or a URL |
fclose() | Closes An Open File Pointer |
2. Reading Files
In order to read a file, the file must first be opened with the appropriate mode to allow you to perform the function(s) that you have planned.
Three different functions are useful for reading files.
Function | Description |
feof() | Tests For End-of-File On a File Pointer |
fgets() | Gets Line From File Pointer |
fread() | Binary-Safe File Read |
filesize() | Gets the Size Of a Given File |
The end-of-file test function, feof(), is commonly used along with the fgets() function to get (read) the entire contents of a file, one line at a time. The filesize() function is commonly used along with the fread() function to read an entire file, otherwise fread() requires that a length/limit be specified and will stop reading the file once that length (number of bytes) has been reached.
Let's look at some examples before we continue.
$FileName = "test.txt";
$FileHandle = fopen($FileName, 'r') or die("File Cannot Be Opened");
$FileData = fread($FileHandle, filesize($FileName));
fclose($FileHandle);
?>
The above example opens a file and stores the entire contents of the file in a variable before closing the file. The variable containing the file's contents can then be used as needed.
$FileName = "test.txt";
$FileHandle = fopen($FileName, 'r') or die("File Cannot Be Opened");
while (!feof($FileHandle)) {
echo fgets($FileHandle) . '<br>';
}
fclose($FileHandle);
?>
The above code opens a file and, while the file still contains unread data, reads each line and displays it before closing the file.
Next, we will learn how to write data to a file.
Summary:
Function | Description |
feof() | Tests For End-of-File On a File Pointer |
fgets() | Gets Line From File Pointer |
fread() | Binary-Safe File Read |
filesize() | Gets the Size Of a Given File |
3. Writing to Files
In order to write to a file, the file must first be opened with the appropriate mode to allow you to perform the function(s) that you have planned.
After the file is opened we can use the fwrite() function to write to the file. Two parameters are required; the file identification handle and the data to write to the file. The syntax is: fwrite(handle, data);
$FileData = "What is the difference between a cat and a comma?\n";
$FileName = "joke.txt";
$FileHandle = fopen($FileName, 'w') or die("File Cannot Be Opened or Created");
fwrite($FileHandle, $FileData);
fclose($FileHandle);
?>
In the above example we used "w" access to open the file, meaning that it was opened for writing only, and any existing contents of the file were erased. Then we wrote our line of text to the file. The "\n" at the end of the string is a carriage return, or newline character, indicating to the file that the line has ended and the file pointer should jump to the next line down. It will not show up when you read the contents of the file.
By opening the file with another access key, such as "a", we can add data to the end of the file without wiping out the existing contents of the file. This action is also known as "appending".
$FileData = "One has the paws before the claws and the other has the clause before the pause.\n";
$FileName = "joke.txt";
$FileHandle = fopen($FileName, 'a') or die("File Cannot Be Opened or Created");
fwrite($FileHandle, $FileData);
fclose($FileHandle);
?>
Now, if we were to read our "joke.txt" file, we would see the following:
What is the difference between a cat and a comma?
One has the paws before the claws and the other has the clause before the pause.
Summary:
Function | Description |
fwrite() | Binary-Safe File Write |
4. Deleting Files
Files can be deleting using the unlink() function. As will all functions that remove data, make double sure that you really want the data gone for good, and that you don't delete the wrong data!
To lessen confusion, make sure that your file is closed before you try to delete/unlink it. Then, a single line of code with do the trick:
unlink('storage.txt');
?>
It's as easy as that!
Summary:
Function | Description |
unlink() | Deletes a File |
5. Filesystem Functions
Filesystem functions allow you to access and to manipulate various aspects of the filesystem. Just about any function you could dream of needing (and some you might never need) can be found in the following list.
Function | Description |
basename | Returns trailing name component of path |
chgrp | Changes file group |
chmod | Changes file mode |
chown | Changes file owner |
clearstatcache | Clears file status cache |
copy | Copies file |
delete | See unlink or unset |
dirname | Returns parent directory's path |
disk_free_space | Returns available space on filesystem or disk partition |
disk_total_space | Returns the total size of a filesystem or disk partition |
diskfreespace | Alias of disk_free_space |
fclose | Closes an open file pointer |
feof | Tests for end-of-file on a file pointer |
fflush | Flushes the output to a file |
fgetc | Gets character from file pointer |
fgetcsv | Gets line from file pointer and parse for CSV fields |
fgets | Gets line from file pointer |
fgetss | Gets line from file pointer and strip HTML tags |
file_exists | Checks whether a file or directory exists |
file_get_contents | Reads entire file into a string |
file_put_contents | Write a string to a file |
file | Reads entire file into an array |
fileatime | Gets last access time of file |
filectime | Gets inode change time of file |
filegroup | Gets file group |
fileinode | Gets file inode |
filemtime | Gets file modification time |
fileowner | Gets file owner |
fileperms | Gets file permissions |
filesize | Gets file size |
filetype | Gets file type |
flock | Portable advisory file locking |
fnmatch | Match filename against a pattern |
fopen | Opens file or URL |
fpassthru | Output all remaining data on a file pointer |
fputcsv | Format line as CSV and write to file pointer |
fputs | Alias of fwrite |
fread | Binary-safe file read |
fscanf | Parses input from a file according to a format |
fseek | Seeks on a file pointer |
fstat | Gets information about a file using an open file pointer |
ftell | Returns the current position of the file read/write pointer |
ftruncate | Truncates a file to a given length |
fwrite | Binary-safe file write |
glob | Find pathnames matching a pattern |
is_dir | Tells whether the filename is a directory |
is_executable | Tells whether the filename is executable |
is_file | Tells whether the filename is a regular file |
is_link | Tells whether the filename is a symbolic link |
is_readable | Tells whether a file exists and is readable |
is_uploaded_file | Tells whether the file was uploaded via HTTP POST |
is_writable | Tells whether the filename is writable |
is_writeable | Alias of is_writable |
lchgrp | Changes group ownership of symlink |
lchown | Changes user ownership of symlink |
link | Create a hard link |
linkinfo | Gets information about a link |
lstat | Gives information about a file or symbolic link |
mkdir | Makes directory |
move_uploaded_file | Moves an uploaded file to a new location |
parse_ini_file | Parse a configuration file |
parse_ini_string | Parse a configuration string |
pathinfo | Returns information about a file path |
pclose | Closes process file pointer |
popen | Opens process file pointer |
readfile | Outputs a file |
readlink | Returns the target of a symbolic link |
realpath_cache_get | Get realpath cache entries |
realpath_cache_size | Get realpath cache size |
realpath | Returns canonicalized absolute pathname |
rename | Renames a file or directory |
rewind | Rewind the position of a file pointer |
rmdir | Removes directory |
set_file_buffer | Alias of stream_set_write_buffer |
stat | Gives information about a file |
symlink | Creates a symbolic link |
tempnam | Create file with unique file name |
tmpfile | Creates a temporary file |
touch | Sets access and modification time of file |
umask | Changes the current umask |
unlink | Deletes a file |