Hàm fopen() mở file hoặc URL, trả về file pointer (resource) để dùng với fread, fwrite, fgets... Trả về FALSE và phát sinh error nếu thất bại. Dùng '@' trước hàm để ẩn error.
Cú pháp
fopen(file_path, mode, include_path, context)
Tham số
file_path – Đường dẫn file hoặc URL (hỗ trợ wrapper: https://, ftp://, phar://...).
mode – Chế độ mở:
"r" – Chỉ đọc, con trỏ đầu file.
"r+" – Đọc/ghi, con trỏ đầu file.
"w" – Chỉ ghi, cắt file về 0, tạo mới nếu chưa có.
"w+" – Đọc/ghi, cắt file về 0, tạo mới.
"a" – Chỉ ghi, con trỏ cuối file, tạo mới nếu chưa có.
"a+" – Đọc/ghi, con trỏ cuối file, tạo mới.
"x" – Tạo mới chỉ ghi, FAIL nếu file đã tồn tại.
"x+" – Tạo mới đọc/ghi, FAIL nếu file đã tồn tại.
Thêm 'b' (binary) hoặc 't' (text) cho Windows (ví dụ: "wb", "rt").
include_path – TRUE/1: tìm trong include_path. Mặc định FALSE.
context – Stream context (tùy chọn).
Giá trị trả về
Trả về file pointer (resource). Trả về FALSE và error nếu thất bại.
Ví dụ 1: Đọc file
<?php
$file_pointer = fopen("new.txt", 'r+') or die("File does not exist");
$res = fgets($file_pointer);
echo $res;
fclose($file_pointer);
?>
Kết quả
The content of the file!
Ví dụ 2: Ghi và đọc lại (w+)
<?php
$file_pointer = fopen("one.txt", "w+");
fwrite($file_pointer, 'demo content');
echo fread($file_pointer, filesize("new.txt"));
fclose($file_pointer);
?>
Kết quả
demo content
Lưu ý: Luôn fclose() sau khi dùng. Mode 'b' khuyến nghị cho binary trên Windows.