Category Archives: PHP-File Handling

PHP-file functions

rename()	Renames a given file	rename("oldname.txt","newname.txt");
unlink()	Deletes a file	unlink("file.txt");
filesize()	Returns the file size of a file	print file("file.txt");
copy()	Copys a file from location to another	copy("olddir/oldname.txt","newdir/newname.txt");

Similar Links:

Link 1

Link 2

PHP – File Read: getc Function

The fgetc() file system function in PHP will return a single character read from a file that is opened using fopen() or fsockopen().

code

<?php
$file = fopen("myfile.txt", "r");
$character = fgetc($file);
fclose($file);
echo $character;
?>
OUTPUT
H

My file contents are “Hello World”. As you can see it returned one single character from that file.

Link One

PHP – File Read: gets Function

The fgets() filesystem function in PHP will return a line from your target file handler. This function can take up to two parameters. The first parameter is your file handler. The second parameter is the character length you wish to read into the line. If no second parameter is supplied it will read until the end of the line.

Code

OUTPUT

Returns 9 character from the file

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 = “filename.txt”;
$fh = fopen($myFile, ‘r’);
$theData = fread($fh, 5);
fclose($fh);
echo $theData;
Display:
kisor
The first five characters from the filename.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 = “filename.txt”;
$fh = fopen($myFile, ‘r’);
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;
Display:
Kisor rawan

PHP – File Write: Appending Data

Using the filename.txt file we created in the File Write lesson , we are going to append on some more data.
PHP Code:
$myFile = “filename.txt”;
$fh = fopen($myFile, ‘a’) or die(“can’t open file”);
$stringData = “laxmi\n”;
fwrite($fh, $stringData);
$stringData “khem\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 filename.txt would now look like this:
phpfresher
Kisor
laxmi
bikesh