Tuesday, January 8, 2008

PHP Files

PHP - Files
Manipulating files is a basic necessity for serious programmers and PHP gives you a great deal of tools for creating, uploading, and editing files.
This section of the PHP tutorial is completely dedicated to how PHP can interact with files. After completing this section you should have a solid understanding of all types of file manipulation in PHP!
PHP - Files: Be Careful
When you are manipulating files you must be very careful because you can do a lot of damage if you do something wrong. Common errors include editing the wrong file, filling a hard-drive with garbage data, and accidentally deleting a file's contents.
It is our hope that you will be able to avoid these and other slipups after reading this tutorial. However, we know that there are so many places where code can take a wrong turn, so we urge you to take extra care when dealing with files in PHP.
PHP - Files: Overview
The presentation of the file lessons will begin with how to create, open, and close a file. After establishing those basics, we will then cover other important file tasks, such as: read, write, append, truncate, and uploading files with PHP.

PHP - File Create
Before you can do anything with a file it has to exist! In this lesson you will learn how to create a file using PHP.
PHP - Creating Confusion
In PHP, a file is created using a command that is also used to open files. It may seem a little confusing, but we'll try to clarify this conundrum.
In PHP the fopen function is used to open files. However, it can also create a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, given that you open the file for writing or appending (more on this later).
PHP - How to Create a File
The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).
Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The file "testFile.txt" should be created in the same directory where this PHP code resides. PHP will see that "testFile.txt" does not exist and will create it after running this code. There's a lot of information in those three lines of code, let's make sure you understand it.
1. $ourFileName = "testFile.txt";
Here we create the name of our file, "testFile.txt" and store it into a PHP String variable $ourFileName.
2. $ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
This bit of code actually has two parts. First we use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w".
Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the $ourFileHandle variable. We will talk more about file handles later on.
3. fclose($ourFileHandle);
We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.
PHP - Permissions
If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.
In the near future Tizag.com will have a more in-depth tutorial on how to use CHMOD to set file permissions.
PHP - File Open
In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into the details of this important function and see what it has to offer.
PHP - Different Ways to Open a File
For many different technical reasons, PHP requires you to specify your intentions when you open a file. Below are the three basic ways to open a file and the corresponding character that PHP uses.
Read: 'r'
Open a file for read only use. The file pointer begins at the front of the file.
Write: 'w'
Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file pointer begins at the start of the file.
Append: 'a'
Open a file for write only use. However, the data in the file is preserved and you begin will writing data at the end of the file. The file pointer begins at the end of the file.
A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file pointer begins at the start of the file. This makes sense because you will usually be reading data from the front of the file.
However, when you open a file for appending, the file pointer is at the end of the file, as you most likely will be appending data at the end of the file. When you use reading or writing functions they begin at the location specified by the file pointer.
PHP - Explanation of Different Types of fopen
These three basic ways to open a file have distinct purposes. If you want to get information out of a file, like search an e-book for the occurrences of "cheese", then you would open the file for read only.
If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the "w" option. This would wipe clean all existing data within the file.
If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the data on to the end. This would be the "a" option.
PHP - File Open: Advanced
There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open a file in such a way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.
Read/Write: 'r+'
Opens a file so that it can be read from and written to. The file pointer is at the beginning of the file.
Write/Read: 'w+'
This is exactly the same as r+, except that it deletes all information in the file when the file is opened.
Append: 'a+'
This is exactly the same as r+, except that the file pointer is at the end of the file.
PHP - File Open: Cookie Cutter
Below is the correct form for opening a file with PHP. Replace the (X) with one of the options above (i.e. r, w, a, etc).
Pseudo PHP Code:
$ourFileName = "testFile.txt";
$fh = fopen($ourFileName, 'X') or die("Can't open file");
fclose($fh);



PHP - File Close
The next logical step after you have opened a file and finished your business with it is to close that file down. You don't want an open file running around on your server taking up resources and causing mischief!
PHP - File Close Description
In PHP it is not system critical to close all your files after using them because the server will close all files after the PHP code finishes execution. However the programmer is still free to make mistakes (i.e. editing a file that you accidentally forgot to close). You should close all files after you have finished with them because it's a good programming practice and because we told you to!
PHP - File Close Function
In a previous tutorial, we had a call to the function fclose to close down a file after we were done with it. Here we will repeat that example and discuss the importance of closing a file.
PHP Code:
$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);
The function fclose requires the file handle that we want to close down. In our example we set our variable "$fileHandle" equal to the file handle returned by the fopen function.
After a file has been closed down with fclose it is impossible to read, write or append to that file unless it is once more opened up with the fopen function.


PHP - File Write
Now that you know how to open and close a file, lets get on to the most useful part of file manipulation, writing! There is really only one main function that is used to write and it's logically called fwrite.
PHP - File Open: Write
Before we can write information to our test file we have to use the function fopen to open the file for writing.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
PHP - File Write: fwrite Function
We can use php to write to a text file. The fwrite function allows data to be written to any type of file. Fwrite's first parameter is the file handle and its second parameter is the string of data that is to be written. Just give the function those two bits of information and you're good to go!
Below we are writing a couple of names into our test file testFile.txt and separating them with a carriaged return.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Bobby Bopper\n";
fwrite($fh, $stringData);
$stringData = "Tracy Tanner\n";
fwrite($fh, $stringData);
fclose($fh);
The $fh variable contains the file handle for testFile.txt. The file handle knows the current file pointer, which for writing, starts out at the beginning of the file.
We wrote to the file testFile.txt twice. Each time we wrote to the file we sent the string $stringData that first contained Bobby Bopper and second contained Tracy Tanner. After we finished writing we closed the file using the fclose function.
If you were to open the testFile.txt file in NOTEPAD it would look like this:
Contents of the testFile.txt File:
Bobby Bopper
Tracy Tanner
PHP - File Write: Overwriting
Now that testFile.txt contains some data we can demonstrate what happens when you open an existing file for writing. All the data contained in the file is wiped clean and you start with an empty file. In this example we open our existing file testFile.txt and write some new data into it.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = "Floppy Jalopy\n";
fwrite($fh, $stringData);
$stringData = "Pointy Pinto\n";
fwrite($fh, $stringData);
fclose($fh);
If you now open the testFile.txt file you will see that Bobby and Tracy have both vanished, as we expected, and only the data we just wrote is present.
Contents of the testFile.txt File:
Floppy Jalopy
Pointy Pinto
In the next lesson we will show you how to get information out of a file by using PHP's read data functions!


PHP - File Read
My apologies for taking so long to actually get to the point where you get information from files. In this lesson we will teach you how to read data from a file using various PHP functions.
PHP - File Open: Read
Before we can read information from a file we have to use the function fopen to open the file for reading. Here's the code to read-open the file we created in the PHP File Write lessons.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
The file we created in the last lesson was named "testFile.txt". Your PHP script that you are writing should reside in the same directory as "text.txt". Here are the contents of our file from File Write.
testFile.txt Contents:
Floppy Jalopy
Pointy Pinto
Now that the file is open, with read permissions enabled, we can get started!
PHP - File Read: fread Function
The fread function is the staple for getting data out of a file. The function requires a file handle, which we have, and an integer to tell the function how much data, in bytes, it is supposed to read.
One character is equal to one byte. If you wanted to read the first five characters then you would use five as the integer.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
Display:
Flopp
The first five characters from the testFile.txt file are now stored inside $theData. You could echo this string, $theData, or write it to another file.
If you wanted to read all the data from the file, then you need to get the size of the file. The filesize function returns the length of a file, in bytes, which is just what we need! The filesize function requires the name of the file that is to be sized up.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
Display:
Floppy Jalopy Pointy Pinto
Note: It is all on one line because our "testFile.txt" file did not have a
tag to create an HTML line break. Now the entire contents of the testFile.txt file is stored in the string variable $theData.
PHP - File Read: gets Function
PHP also lets you read a line of data at a time from a file with the gets function. This can or cannot be useful to you, the programmer. If you had separated your data with new lines then you could read in one segment of data at a time with the gets function.
Lucky for us our "testFile.txt" file is separated by new lines and we can utilize this function.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
testFile.txt Contents:
Floppy Jalopy


PHP - File Delete
You know how to create a file. You know how to open a file in an assortment of different ways. You even know how to read and write data from a file!
Now it's time to learn how to destroy (delete) files. In PHP you delete files by calling the unlink function.
PHP - File Unlink
When you view the contents of a directory you can see all the files that exist in that directory because the operating system or application that you are using displays a list of filenames. You can think of these filenames as links that join the files to the directory you are currently viewing.
If you unlink a file, you are effectively causing the system to forget about it or delete it!
Before you can delete (unlink) a file, you must first be sure that it is not open in your program. Use the fclose function to close down an open file.
PHP - Unlink Function
Remember from the PHP File Create lesson that we created a file named testFile.txt.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fclose($fh);
Now to delete testFile.txt we simply run a PHP script that is located in the same directory. Unlink just needs to know the name of the file to start working its destructive magic.
PHP Code:
$myFile = "testFile.txt";
unlink($myFile);
The testFile.txt should now be removed.
PHP - File Append
So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.
PHP - File Open: Append
If we want to add on to a file we need to open it up in append mode. The code below does just that.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');
If we were to write to the file it would begin writing data at the end of the file.
PHP - File Write: Appending Data
Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);
You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.
The contents of the file testFile.txt would now look like this:
Contents of the testFile.txt File:
Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2
PHP - Append: Why Use It?
The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.
A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!

PHP - File Truncate
As we have mentioned before, when you open a file for writing with the paramater 'w' it completely wipes all data from that file. This action is also referred to as "truncating" a file. Truncate literally means to shorten.
PHP - File Open: Truncate
To erase all the data from our testFile.txt file we need to open the file for normal writing. All existing data within testFile.txt will be lost.
PHP Code:
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w');
fclose($fh);
PHP - Truncate: Why Use It?
Truncating is most often used on files that contain data that will only be used for a short time, before needing to be replaced. These type of files are most often referred to as temporary files.
For example, you could create an online word processor that automatically saves every thirty seconds. Every time it saves it would take all the data that existed within some HTML form text box and save it to the server. This file, say tempSave.txt, would be truncated and overwritten with new, up-to-date data every thirty seconds.
This might not be the most efficient program, but it is a nice usage of truncate.

PHP - File Upload
A very useful aspect of PHP is its ability to manage file uploads to your server. Allowing users to upload a file to your server opens a whole can of worms, so please be careful when enabling file uploads.
PHP - File Upload: HTML Form
Before you can use PHP to manage your uploads, you must first build an HTML form that lets users select a file to upload. See our HTML Form lesson for a more in-depth look at forms.
HTML Code:


Choose a file to upload:



Here is a brief description of the important parts of the above code:
enctype="multipart/form-data" - Necessary for our to-be-created PHP file to function properly.
action="uploader.php" - The name of our PHP page that will be created, shortly.
method="POST" - Informs the browser that we want to send information to the server using POST.
input type="hidden" name="MA... - Sets the maximum allowable file size, in bytes, that can be uploaded. This safety mechanism is easily bypassed and we will show a solid backup solution in PHP. We have set the max file size to 100KB in this example.
input name="uploadedfile" - uploadedfile is how we will access the file in our PHP script.
Save that form code into a file and call it upload.html. If you view it in a browser it should look like this:
Display:
Choose a file to upload:
After the user clicks submit, the data will be posted to the server and the user will be redirected to uploader.php. This PHP file is going to process the form data and do all the work.
PHP - File Upload: What's the PHP Going to Do?
Now that we have the right HTML form we can begin to code the PHP script that is going to handle our uploads. Typically, the PHP file should make a key decision with all uploads: keep the file or throw it away. A file might be thrown away from many reasons, including:
The file is too large and you do not want to have it on your server.
You wanted the person to upload a picture and they uploaded something else, like an executable file (.exe).
There were problems uploading the file and so you can't keep it.
This example is very simple and omits the code that would add such functionality.
PHP - File Upload: uploader.php
When the uploader.php file is executed, the uploaded file exists in a temporary storage area on the server. If the file is not moved to a different location it will be destroyed! To save our precious file we are going to need to make use of the $_FILES associative array.
The $_FILES array is where PHP stores all the information about files. There are two elements of this array that we will need to understand for this example.
uploadedfile - uploadedfile is the reference we assigned in our HTML form. We will need this to tell the $_FILES array which file we want to play around with.
$_FILES['uploadedfile']['name'] - name contains the original path of the user uploaded file.
$_FILES['uploadedfile']['tmp_name'] - tmp_name contains the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.
Now we can finally start to write a basic PHP upload manager script! Here is how we would get the temporary file name, choose a permanent name, and choose a place to store the file.
PHP Code:
// Where the file is going to be placed
$target_path = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
$_FILES['uploadedfile']['tmp_name'];
NOTE: You will need to create a new directory in the directory where uploader.php resides, called "uploads", as we are going to be saving files there.
We now have all we need to successfully save our file to the server. $target_path contains the path where we want to save our file to.
PHP - File Upload: move_uploaded_file Function
Now all we have to do is call the move_uploaded_file function and let PHP do its magic. The move_uploaded_file function needs to know 1) The path of the temporary file (check!) 2) The path where it is to be moved to (check!).
PHP Code:
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
" has been uploaded";
} else{
echo "There was an error uploading the file, please try again!";
}
If the upload is successful, then you will see the text "The file filename has been uploaded". This is because $move_uploaded_file returns true if the file was moved, and false if it had a problem.
If there was a problem then the error message "There was an error uploading the file, please try again!" would be displayed.

No comments: