Hàm fopen
Hàm fopen mở file hoặc URL và trả về một con trỏ tới resource. Tham số đầu tiên hàm nhận đường dẫn tới file hoặc URL, tham số thứ hai - chế độ mở. Trong trường hợp thành công trả về con trỏ file, trong trường hợp lỗi - false.
Cú pháp
fopen(filename, mode, [use_include_path], [context]);
Ví dụ
Mở file để đọc:
<?php
$res = fopen('file.txt', 'r');
var_dump($res);
?>
Kết quả thực thi mã:
resource(5) of type (stream)
Ví dụ
Mở file để ghi (nếu file không tồn tại - nó sẽ được tạo):
<?php
$res = fopen('newfile.txt', 'w');
var_dump($res);
?>
Kết quả thực thi mã:
resource(5) of type (stream)
Ví dụ
Thử mở một file không tồn tại để đọc:
<?php
$res = fopen('nonexistent.txt', 'r');
var_dump($res);
?>
Kết quả thực thi mã:
false
Ví dụ
Mở một URL để đọc:
<?php
$res = fopen('https://example.com', 'r');
var_dump($res);
?>
Kết quả thực thi mã:
resource(5) of type (stream)