Tuesday, July 17, 2007

php: file create, read, write, open, close and delete

I have to figure out how to manipulate file in php in order to automate my database converter. The problem here is the main database is using interbase while my local database is using mysql.

This is just a note for my references:

The typical pattern of manipulating file is open, do write or read then close file.

Create & Open File
Open and creating a file are using the same command in php.

$fileName = 'theFile.txt';
$fileHandler = fopen( $fileName, 'X' ) or die( "can't open file! );

replace X with:
r : to read a file, the pointer starts from the beginning of the file.
w : to write to the file, overwrite the previous content.
a : to wrote to the file, appending the new content to the current file.
r+ : open a file to be read from and write to, the pointer starts from the beginning of the file.
w+ : same as r+, but the content of the file becomes overwrite (empty).
a+ : same as r+, only the pointer is at the end of the file.

die( "can't open file! ) needed to stop the process below. Otherwise, errors are pop up for the following file manipulation commands.


Read File

$txt = fread( $fileHandler, n );

where n can be:
integer, for example 10, to read the first 10 bytes [or characters as 1 byte = 1 character], or
if you want to read the all contents of the file, replace n with filesize( $fileName );


Write File

fwrite( $fileHandler, $txtToWrite );


Delete [Unlink] File
In php, deleting a file is equal to unlink the file, if there is no more link to the file object, the system will forget of its existence.

unlink( $fileName );


Closing File

fclose( $ fileHandler );


Actually I summarize that from http://www.tizag.com, solely for the purpose of maintaining single place documentation.

1 comment:

Unknown said...

how can i open a file that have a image and text with php