fopen()
function is used to open file or URL and returns resource. This function gives you more options than the readfile()
function. The fopen()
function accepts two arguments: $filename
and $mode.
The $filename
represents the file to be opended and $mode
represents the file mode for example read-only, read-write, write-only etc.JPEG = Joint Photographic Experts Group
GIF = Graphics Interchange Format
PNG = Portable Network Graphics
PSD = Photoshop Document
SVG = Scalable Vector Graphics
<!DOCTYPE HTML>
<html>
<head>
<title>File Handling - fopen()</title>
</head>
<body>
<?php
$myfile = fopen("MY_FILe.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("MY_FILE.txt"));
fclose($myfile);
?>
</body>
</html>
Mode | Description |
r | Opens file in read-only mode. It places the file pointer at the beginning of the file. |
r+ | Opens file in read-write mode. It places the file pointer at the beginning of the file. |
w | Opens file in write-only mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file. |
w+ | Opens file in read-write mode. It places the file pointer to the beginning of the file and truncates the file to zero length. If file is not found, it creates a new file. |
a | Opens file in write-only mode. It places the file pointer to the end of the file. If file is not found, it creates a new file. |
a+ | Opens file in read-write mode. It places the file pointer to the end of the file. If file is not found, it creates a new file. |
x | Creates and opens file in write-only mode. It places the file pointer at the beginning of the file. If file is found, fopen() function returns FALSE. |
x+ | It is same as x but it creates and opens file in read-write mode. |
The PHP read functions are given below.
fread($file, filesize("MY_FILE.txt"));
<!DOCTYPE HTML>
<html>
<head>
<title>PHP Read File - fread()</title>
</head>
<body>
<?php
$filename = "MY_FILE.txt";
$fp = fopen($filename, "r");//open file in read mode
$contents = fread($fp, filesize($filename));//read file
echo "<pre>$contents</pre>";
fclose($fp);
?>
</body>
</html>
fgets()
function is used to read a single line from a file.string fgets ( resource $file [, int $file_name ] )
<!DOCTYPE HTML>
<html>
<head>
<title>Read Single Line - fgets()</title>
</head>
<body>
<?php
$file = fopen("MY_FILE.txt", "r");//open file in read mode
echo fgets($file);
fclose($file);
?>
</body>
</html>
fgetc()
function is used to read a single character from a file.
string fgetc ( resource $file )
<!DOCTYPE HTML>
<html>
<head>
<title>Read Single Character - fgetc()</title>
</head>
<body>
<?php
$file = fopen("MY_FILE.txt", "r");//open file in read mode
while(!feof($file)) {
echo fgetc($file);
}
fclose($file);
?>
</body>
</html>