Use fopen() when you need a file handle for controlled or incremental reading. Always check that the handle was created successfully, and close it with fclose() when finished.
$file = __DIR__ . '/data.txt';
$handle = fopen($file, 'r');
if ($handle !== false) {
while (($line = fgets($handle)) !== false) {
echo htmlspecialchars($line) . '<br>';
}
fclose($handle);
}This example shows the recommended starting pattern. Continue below for variations, explanation and the original practical examples.
//$filename = "my_file.txt"; // Inside same directory
$filename = "D://my_dir//y23_02.txt"; // Path to file
$fd = fopen ($filename, "r"); // opening the file in read mode
$contents = fread ($fd, filesize($filename)); // reading the content
fclose ($fd);
print($contents);
file:mode:r:r+:w:w+:a:a+:x:x+:c:c+:e:use_include_path:context:$filename = "http://localhost/plus2net/php_tutorial/site_map-file.php"; // local url
$fd = fopen ($filename, "r"); // opening the file in read mode
$contents = fread ($fd, 10000); // reading the content of the
fclose ($fd);
print($contents);
We will be using fread() function to read the content by using a file pointer. Fread()reads up to length bytes from the file pointer
referenced by fd.
<?Php
$filename = "delete.htm"; // This is at root of the file using this
script.
$fd = fopen ($filename, "r"); // opening the file in read mode
$contents = fread ($fd, filesize($filename)); // reading the content of the
file
fclose ($fd);
// Closing the file pointer
echo $contents;
// printing the file content of the file
?>
Opening a URL by file_get_contents()
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Nicholas | 17-03-2010 |
| Great lessons. Thank you very much :-) | |
| Ram | 28-07-2010 |
| Very simple & useful.., Thanks a lot | |
| ravi | 08-12-2012 |
| this code open the file in read format but the file is in encrypted format..its unreadable.please tell me the solution of this. | |
06-02-2023 | |
| this is amazing | |