fopen(): PHP File open to read internal file

//$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:
Required path to the file or URL.
mode:
Type of access required.
r:
Read only.
r+:
Open for reading and writing
w:
writing only
w+:
Read and writing
a:
Adding data ( writing only ) at end of file
a+:
Adding data ( read and writing ) at end of file
x:
Create and open for writing
x+:
Create adn open for reading and writing
c:
Open for writing.
c+:
Open for reading and writing.
e:
Set close-on-exec flag on the opened file descriptor.
use_include_path:
Optional , to search for file in include path
context:
Optional , context stram resource
By using fopen we can read any external url also. We can write to a file by using fwrite function.

Using URL

$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.
Reading stops when length bytes have been read or EOF is reached,whichever comes first.

We can also used the function filesize() to know the size of the file and used it in the fread function.

<?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()



File Directory Functions
PHP
Subscribe to our YouTube Channel here



plus2net.com







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




PHP video Tutorials
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2025   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer