0
PHP File Handling
Posted by jujur
on
5:21 AM
Bab 16
PHP File Handling
Dalam PHP,
fungsi fopen() digunakan untuk membuka file.
Membuka File
Program16-1.php
<html>
<body>
<?php
$file=fopen("welcome.txt","r");
?>
</body>
</html>
|
Mode
pembukaan file
Mode
|
Keterangan
|
r
|
Read only. Starts at the beginning of the file
|
r+
|
Read/Write. Starts at the beginning of the file
|
w
|
Write 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
|
a
|
Append. 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
|
x
|
Write 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
|
Catatan: Jika
fopen() tidak dapat membuka file, maka akan mengembalikan nilai 0 (false).
Program16-2.php
<html>
<body>
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
?>
</body>
</html>
|
Menutup File
Program16-3.php
<?php
$file = fopen("test.txt","r");
//some code to be executed
fclose($file);
?>
|
Memeriksa EOF (End Of File)
Catatan: Kita
tidak dapat membaca file yang terbuka dalam mode w, a, dan x!
if (feof($file)) echo "End of file";
|
Membaca file baris per baris (fgets())
Program16-4.php
<?php
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
|
Membaca file karakter per karakter (fgetc())
Program16-5.php
<?php
$file=fopen("welcome.txt","r") or exit("Unable to open file!");
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>
|