Saturday, October 1, 2011

File Operation in PHP (Part 2)

Assalamualaikum and Selamat Sejahtera

Today we will learn these : fopen(),    feof()    ,fgets()    ,fclose().

1.Use the previous post text file.

2.Open the "www" folder,make a new PHP file called : openfile.php.Inside this file,write this code below.



3..Save it and run this file ,by type at the browser's address : http://localhost/openfile.php.


4.So,as we run it it will display this on the browser :

What we usually expect it,it will display the content of file.But it only display this words.For your information,this words are the pointer for phpFILE.txt. So,how to display it?well we will use the next function which is fgets(). Here is the code.

So,before run this file.Open the phpFILE.txt first and then add another this statement :


Okey,now run it....and of course la,the browser will display like this :

So,the function that we will discuss is feof().The meaning of feof is "file end of file".So,in while loop,it will keep asking the function "file end of file" either its already end of file yet.Function "file end of file" will be true when it reach at end of file.That why if we type while like this : while( feof ($file_to_handle) ) ,it will only show the end line of file only.

Furthermore,fopen(first parameter , second parameter) function for to open the file.The first parameter is for the name of file.The second parameter is for mode ,"r" is means read.Here is example of modes:


ModesDescription
rRead only. Starts at the beginning of the file
r+Read/Write. Starts at the beginning of the file
wWrite only. Opens and clears the contents of file; or creates a new file if it doesn't exist
w+Read/Write. Opens and clears the contents of file; or creates a new file if it doesn't exist
aAppend. Opens and writes to the end of the file or creates a new file if it doesn't exist
a+Read/Append. Preserves file content by writing to the end of the file
xWrite only. Creates a new file. Returns FALSE and an error if file already exists
x+Read/Write. Creates a new file. Returns FALSE and an error if file already exists


That all for today
Thank you!