w3reference home
PHP Tutorial


Bookmark and Share

PHP File handling

There are many built-in functions for handling files in PHP. It is useful when your HTML form needs to upload some file to the server. You can read, write, delete, and get lots of information on files through the use of these functions. You need to be very careful while handling files. In case you edit the wrong file, you will loose your data.
A point to note: Before you start working with files, you have to make sure that you have the right permissions that will allow you to manipulate them. So while you’re trying to figure out why you can’t delete a file, it may be because the server doesn’t allow you to do that.

Creating Files

For understanding files, first a file must exist. PHP does not have a separate command for creating files. The fopen() command to open files is used to create files also. We will see how this command works in the section that follows.

Opening Files

A file can be opened by using the fopen() command. It takes two parameters. The first parameter contains the name/path of the file to be opened and the second parameter contains the mode in which to open the file. The various modes in which a file can be opened are given below:
Mode Description
r Read only. The file is opened for read only purpose with the pointer at the beginning of the file.
r+ Read/Write. The file is opened in read/write mode with the pointer at the beginning of the file.
w Write only. The file is opened in write only mode and the earlier content is erased. If the file does not already exist, it is created.
w+ Read/Write. The file is opened and the earlier content deleted. If the file does not already exist, it is created.
a Append. The file is opened and the pointer points to the end of the file. If the file does not already exist, it is created.
a+ Read/Append. The pointer is at the end of the file but the earlier content is preserved. If the file does not already exist, it is created.
x Create only. The file is created if it does not already exist. Returns FALSE if the file exists already.
x+ Create/Write. The file is created if it does not exist otherwise returns FALSE.
touch(“newfile.txt”);
The above command unlink(“oldinfo.txt”); //delete a file Now that you know how to create a file, you should learn how to access it. This is done using the “fopen()” function, with requires a string containing the file path and a string containing the mode in which the file is about to be opened, which tells “fopen()” to open a file for reading, writing, or both. The complete list of the available modes can be found in the PHP documentation. “fopen()” return an integer, also known as a file pointer, which should be assigned to a variable. This will be used later on to work with the opened file. If a file cannot be open for whatever reason, “fopen()” returns FALSE. After you’re done with the file, you should remember to close it with “fclose()”, passing as an argument the file pointer.
$oldfp = fopen(“oldinfo.txt”, “r”); //opens a file for reading
if(!$fp = fopen(“newinfo.txt”, “w”)) //tries to open a file for writing
die(“Error opening file!”); //terminates execution if it cannot open the file
fclose($oldfp);
Reading from files is done with “fgets()”, which reads data from a file until it reaches a new line “n”, an EOF (end-of-file), or a specified length, in this order. So if you specify 4096 bytes but “fgets()” first reaches a new line, it stops further reading. You should know that after each reading or writing to a file, PHP automatically increments an index which holds the current position in the file. So if you have just opened a file, and then read 100 bytes, the next time you will want to read something else using the same file pointer, PHP will continue from where the 101st byte. The “fgetc()” is similar to “fgets()”, except that it returns only a single character from a file every time it is called. Because a character is always 1 byte in size, “fgetc()” doesn’t require a length argument.
$text = fgets($fp, 2000); //reads 2000 bytes at most
$chr = fgetc($fp); //reads 1 byte only
While you can read lines using “fgets()”, you need a way of telling when you have reached the end-of-file, so you won’t continue reading without any results. This is accomplished with the “feof()” functions, which returns “TRUE” or “FALSE”, weather the position of a file pointer is at the end of it. You now have enough information to read a file line by line:
$filename = "test.txt";
$fp = fopen($filename, "r") or die("Couldn’t open $filename");
while(!feof($fp))
{
  $line = fgets($fp);
  print "$line
"; } fclose($fp);
While “fgets()” works well around text files, you may sometimes want more functionality for your script. The “fread()” functions returns the specified amount of data from a file, and doesn’t take into consideration the end-of-line “n”, like “fgets()”. “fread()” also starts from the current file position, but if you’re not happy with it, you can always change it using the “fseek()” function.
fseek($fp, 100); //moves the file pointer to the 100th byte
print(fread($fp, 15)); //outputs 15 bytes
Any writing to a file is done with the use of “fwrite()” or “fputs()” functions, which both use a file pointer and a string to perform the writing:

fwrite($fp, “Hello from PHP!”);

fputs($fp, “Hello again from PHP!”);
So far, these functions were great with a single user. However, on public web-sites, with many users accessing your scripts at the same time, your files could quickly become corrupt. PHP offers the “flock()” function, which will lock a file and won’t allow other processes to write or read the file while the current process is running. “flock()” requires a file pointer and an integer to do this:
flock($fp1, 1); //shared lock – allows read, doesn’t allow write

flock($fp2, 2); //exclusive lock – doesn’t allow neither read, nor write

flock($fp3, 3); //release lock – releases a shared or exclusive lock
There are a lot of other functions that you can use with files like: testing functions – “file_exists()”, “is_file()”, “is_dir()”, “is_readable()”, “is_writeable()”, “is_executable()”; functions that return information on files: “filesize()”, “fileatime()”, “filemtime()”, “filectime()”. You can figure out what the function does by just reading its name; more information about them can be found in the PHP documentation.
Code Validator
Learn FTP
Color finder
Link Checker
Free web designs
Coming soon!
Interview Questions...
'w3reference : Learn by examples ... Advanced to beginner's tutorials ...'
Ajax: AJAX tutorial1 | Apache: Apache HTTP Server | Restarting Apache | CSS: CSS Border | CSS Syntax | CSS Selector | CSS Comment | CVS: CVS Release | CVS Login | CVS Logout | CVS Annotate | Databases: Rolap Tutorial | OLAP Tutorial | OLTP Tutorial | data warehousing | Expect: HTML: html | Linux: Dot (.) conf files | Linux Mount Point | Linux Filesystem | SSH Tutorial | Linux Commands: cal | cat | cfdisk | chroot | MySQL: MySQL Commands | PHP: PHP Basics | PHP Variables | PHP Output (echo/print) | PHP String Concat | PL/SQL: PL/SQL Data Types | PL/SQL Control Structures | PL/SQL File Extensions | PL/SQL DBMS_OUTPUT package | Python: My first Python program | Shell: Starting Bash | Bash Redirection | Bash Pipes | Bash Variables | SQL: SQL Transactions | SQL Constraints | SQL Drop | SQL Union & Union All | SVN: svn architecture | SVN Repository | SVN Import | SVN Checkout | Tech: soap | Web Designing: Web Hosting | HTML/XHTML/CSS code validator | Learn FTP | Search Engine Optimization Tips | www: XML: XML vs HTML | XML Syntax | XML Tags, Elements and Attributes | XML Namespaces |
Sitemap | Disclaim | Privacy Policy | Contact | ©2007-2009 w3reference.com All Rights Reserved.