• Tidak ada hasil yang ditemukan

Pertemuan 08 PHP Files

N/A
N/A
Protected

Academic year: 2017

Membagikan "Pertemuan 08 PHP Files"

Copied!
3
0
0

Teks penuh

(1)

Praktikum Aplikasi Web

Pertemuan-8

PHP Files

Percobaan-1 : open a file and read its contents (fopen)

//first we tell php the filename

$file = 'fileDataEx.txt';

// then we try to open the file, using the r mode, for reading only $fp = fopen($file, 'r') or die('Couldn\'t open file!');

// read file contents

$data = fread($fp, filesize($file)) or die('Couldn\'t read file!'); // close file

fclose($fp);

// print file contents

print "The data in the file is \"".$data."\"";

//The data in the file is "This is line one. This is line two. This is line three."

Percobaan-2 : open a file and append data fwrite

$filename = 'fileDataEx.txt';

$addcontent = "This is line 4\n"; //this is the content to append to the file // Try to open the file

$handle = fopen($filename, 'a') ordie ("Can't open file ($filename)"); // Try to write to open file

fwrite($handle, $addcontent) ordie ("Can't write to file ($filename)"); $handle = fopen($filename, 'r') or die('Couldn\'t open file!');

$data = fread($handle, filesize($filename)) ordie ('Couldn\'t read file!');

echo "Success, wrote ($somecontent) to file ($filename)";

(2)

fclose($handle);

//Success, wrote () to file (fileDataEx.txt)The new file now is: This is line one. This is line two. This is line three.

Percobaan-3 : Reading a file into an array using file()

$file = 'fileDataEx.txt';

// read file into array

$data = file($file) or die('Could not read file!'); // show the new contents of the file

foreach ($data as $line) {

echo $line."<br>";

}

(3)

Percobaan-4 : Reading and writing to files using fputs and fgets

//fgets

$handle = fopen("fileDataEx.txt", "r"); //open file for reading

echo "Using fgets<br>";

//Using fgets

while (!feof($handle)) { //while not end of file

$buffer = fgets($handle, 4096); //use fgets with file handle, specifying size

/*4096 is just the size of the longest line likely, and fgets stops at the end of the line or 4096. Without some size here, fgets might stop at a zero byte in the line rather than the end of the line*/

echo $buffer; //print out the line

}

fclose($handle); //close the file

// File Contents: This is line one. This is line two. This is line three. This is line 4 This is line 4 This is line 4

//fputs

$handle = fopen("fileDataEx2.txt", "a") ordie ("Couldn't open the file"); //open file for reading

//make a string

$string="apples pears

oranges "; //Using fputs

Referensi

Dokumen terkait