Clixint Tech. Blog
Where we post most up-to-date information about our products and other technologies.
Reading and Wrting Files with PHP

Ali Imran 0
Working as Chief Operating Officer
Posted in PHP & MySQL
04
Apr
2012

PHP follows almost same way of writing and manipulating files as in standard C. That is why it becomes so easy for a developer with C language background to create php application that uses files to save and retrieve data. It is a short tutorial that will get you started with writing and manipulating text files.

To open a file either for writing, manipulating (adding new data, or appending new data at end of file), we use single function called fopen, but the second argument of the function changes accordingly.

For example:

$F = fopen("myfile.txt","w");

Here the second argument passed was "w" only, which means write the file, if it does not exists then create it, and if does not exist create new file.

Now, if a file with name myfile.txt already exists, it will be rewritten and all of its bytes are lost, if it was not existing a new file with name myfile.txt is created.

The second argument (we used "w") is the file opening mode, is dependent upon your requirement. In general disadvantage of using "w" as mode is if your ifle already exists, it is rewritten, and you loose all existing bytes. So it is recommended that you use mode "w" only when you need to create a new file or really wish to turn filesize to 0 (zero).

Second mode is "r", which is using for reading and writing. Using this filemode you can open a file for reading and writing. Although modes "r" as well as (append "a") allows read and write but they do not affect the file while opening it, so the "w" also allows writing + reading but as mentioned, it rewrites the file.

So, to open a file for reading and writing we will write:

$F = fopen("myfile.txt","r");

And same if we need to open a file which starts writing data to the end of file (appends data), we will srite:

$F = fopen("myfile.txt","a");

Remember : With both of these modes you can read as well as write data anywhere in the file.

Now question appears, if I open a file with mode "r" now I have ended up reading soem data, how can I force my script to start writing data on the end of file ?

Two answers:
1. If you have read entire data, the next writing automatically starts at the end of file.
2. If you read data less then the file size, you must be somewhere within file, and if you start writing data, the script will write data to the last position of data you ended up reading with.

To obtain filesize we use a function filesize, to which we only pass name of file along-with path (if not current directory) and it returns us the size of the file in bytes. e.g.

$size = filesize("myfile.txt");

Now, when you have opened a file for reading and you wish to jump to a certain position (in this case end of file), you use a function fseek which lets you jump within file to any possible position. e.g.

suppose your file size is 10 bytes, you read very first two characters. Now you wish to jum pto the end of file.

//reading done, assume $F is file variable
$size = filesize("myfile.txt");
fseek($F, $size); //now we are at end of file
//start writing here

The same we will do when we need to jump to the start of file as:
fseek($F,0); //0 means very first byte position

Bytes position in a file have zero based indexes, 0 means 1st character, 9 means 10th character and so on.

Now come to core of reading and wrting:

Writing is very simple, as I have mentioned in all above talk the writing starts where pointer (position) currently is so the reading too.

Example 1: Create new file and write string "My name is Ali" in it

$F = fopen("myfile.txt","w");

fwrite($F,My name is Ali);

fclose($f);


In this example you see two new functions fwrite and fclose.

fwrite is used to write something in a file at current position, since we created new file so writing starts at very first byte autoatically. And fclose is used to stop using a file anymore. This is necessary, becuase there is always a limit of opened files in operating system, so if your script is used much and leaves every file open without closing, it will results in no more file openable until system restart, either an http server (a web host) and/or local host. So, a new file is created and stirng "My name is Ali" is written in it (14 bytes written).


Example 2: Read first 7 bytes from file we created in example 1 and print them to browser

$F = fopen("myfile.txt","r");

$data = fread($F, 7);

fclose($f);

print $data;

In this example you encounter a ne function, called fread. This function is used to read specific number of bytes from a file. Its first argument is the file variable, and second is number of bytes to read. So we passed 7, becuase our rquirement at this time, is to read 7 bytes only. This function returned us the bytes read and we simpyl displayed them using print function, so it will display "My name" only the first7 bytes we read. Take a look at next example

Example 3: Read all data from file we created in example 1 and print it to browser

$F = fopen("myfile.txt","r");

$size = filesize("myfile.txt");

$data = fread($F, $size);

fclose($f);

print $data;


In this example we used function filesize, which returned us the exact file size in bytes, we saved that size in a variable $size and then passed it to fread as second argument, so that the fread function reads all the data in file. I think it is simple to understand. It will display "My name is Ali" in the browser.

Modifying data

Example 4: Jump to byte # 12 and write string "Imran"

$F = fopen("myfile.txt","r");

fseek($F, 11);

fwrite($F,"Imran");

fclose($f);

print $data;


We opened file, jumped to byte number 12 using fseek function. Why used 11 when we need to start modifying from byte 12 ? Because I already mentioned that bytes in a file are accessed using zero based index, 11 means 12, 59 means 60, and 0 means 1st byte. Now run the example 3 and you will see the display in browser is "My name is Imran", which means we successfully have modified the file.

Example 5: Add string ". My age is 30" to the end of file we created in example 1

$F = fopen("myfile.txt","a"); //note "a"

fwrite($F,". My age is 30");

fclose($f);

print $data;

We opened file with append mode, using "a" as second argument to function fopen, which automatically takes position to the end of file, s owe don't need to use fseek in this regards. Now if you repeat running example 3 you will get the output as "My name is Imran. My age is 30".

Extra things:

1. Another method to read entire file data in a variable

$data = get_file_contents("myfile.txt");

2. Read text file as an array of strings, where each line of text is an ite of array

$arr = file("myfile.txt");

3. If you don't have above function in your php distribution, use following to read entire data
$data = implode("",file("myfile.txt"));

4. to delete a file

unlink("myfile.txt");

5. read page from internet
pass url instead of filename in any of first 3 examples.

I hope I have explained some. Let me know if you have any question.

Share this post : Facebook



0 Response(s) to Reading and Wrting Files with PHP


Be the first one to post a comment.

Post a Comment ! All comments are moderated
Please fill the form below to enter your comment.

Enter Your Name
Enter Your Email
Enter Your Website



Clixint Technologies

Clixint Technologies provides the most cost effective and user friendly IT solutions with a clear view and direct approach, keeping our customer's audience in mind. Contact Us


Blog Categories


Building Businesses Since 2002

Clixint Technologies. is a registered international firm focused on conceiving, developing and distributing customer-focused IT solutions for the large as well as small to mid-sized businesses that are serious about excelling and achieving success. We provide conceptual, functional and presentational development for the global business community through out-of-the-box web strategy, design and technology solutions. We have been delivering quality products since 2002.
Privacy Policy
Terms & Conditions