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

phpfopen(filename, mode, [use_include_path], [context]);

Ví dụ

Mở file để đọc:

php<?php
  $res = fopen('file.txt', 'r');
  var_dump($res);
?>

Kết quả thực thi mã:

phpresource(5) of type (stream)

Ví dụ

Mở file để ghi (nếu file không tồn tại - nó sẽ được tạo):

php<?php
  $res = fopen('newfile.txt', 'w');
  var_dump($res);
?>

Kết quả thực thi mã:

phpresource(5) of type (stream)

Ví dụ

Thử mở một file không tồn tại để đọc:

php<?php
  $res = fopen('nonexistent.txt', 'r');
  var_dump($res);
?>

Kết quả thực thi mã:

phpfalse

Ví dụ

Mở một URL để đọc:

php<?php
  $res = fopen('https://example.com', 'r');
  var_dump($res);
?>

Kết quả thực thi mã:

phpresource(5) of type (stream)

Xem thêm