Membuat, Membuka, Membaca, Menulis, Mengkopi, Mengganti Nama, Menutup, dan Menghapus file menggunakan Program PHP

Kali ini kita akan membahas manipulasi file-file seperti text, html, xml, swf dan objek file lainnya menggunakan operasi php untuk mencapai sesuatu yang kita harapkan selanjutnya.





Membuat File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file

Membuka File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //open file for writing ('w','r','a')...

Membaca File

$my_file = 'file.txt';
$handle = fopen($my_file, 'r');
$data = fread($handle,filesize($my_file));

Menulis File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
$data = 'This is the data';
fwrite($handle, $data);

Menambahkan string ke dalam File

$my_file = 'file.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
$data = 'New data line 1';
fwrite($handle, $data);
$new_data = "\n".'New data line 2';
fwrite($handle, $new_data);

Mengkopi File

$my_file_source = 'file.txt'; $my_file_copy = 'folder/file_copy.txt';
$copy_file = copy($my_file_source, $my_file_copy);;

Mengganti Nama File

$first_file = 'file1.txt'; $second_file = 'file2.txt';
$rename_file = rename($first_file, $second_file);


Menutup File

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
//write some data here
fclose($handle);

Menghapus File

$my_file = 'file.txt';
unlink($my_file);

Sampai jumpa dengan tutorial php berikutnya..!
Previous
Next Post »