You must open that file before reading and writing or creating a file. To open a file using PHP, you have to use the PHP fopen() function.
Syntax of the
<?php // File Name $filename = 'c:\folder\resource.txt'; // Mode (r = 'read mode') $mode = "r"; // Optional Parameter $use_include_path = true; $myFile = fopen($filename,$mode); ?>
.phpfile and the
.txtfile are in the same folder, then you don’t have to enter the full path, just enter the filename.
📝 The fopen() function will return an error if the file does not exist which you want to open, or if the file does not have the read or write permission.
Example of the
Not only the .txt file, You can open every type of file using the
fopen() function. Such as image file (.png, .gif), zip file (.zip) etc.
<?php // OPENING A FILE (WITH THE READ MODE) $myFile = fopen('c:\folder\resource.txt','r'); // OPENING A URL (WITH THE READ MODE) $myURL = fopen("http://example.com/",'r'); // OPENING A IMAGE FILE $myImage = fopen('c:\folder\my.png', 'r'); //OPENING A FILE THROUGH FTP URL $myFTPFile = fopen("ftp://user:[email protected]/file.txt",'r'); ?>
| ||Open for reading only. The file pointer starts at the beginning of the file.|
|Open for reading and writing. The File pointer starts at the beginning of the file.|
|Open for writing only. The file pointer starts at the beginning of the file and Erases the existing contents of the file. If the file does not exist, it will create it.|
|It works the same as |
|Open for writing only. The file pointer starts at the end of the file. If the file does not exist, it will create it. fseek() has no effect, writes are always appended.|
|It works the same as |
|It will create a new file, and open that file for writing only. if the file already exists, it will return FALSE and an error.|
|It has the same behavior as |
The different operating system has different line-ending conventions. When you write a text file and want to insert a line break, you need to use the correct line-ending character(s) according to your operating system –
Windows offers a text-mode translation flag
't' that will transparently translate \n to \r\n when working with the file. In contrast, you can also use ‘b’ to force binary mode, which will not translate your data. To use these flags, specify either
't' as the last character of the mode parameter.
You should use the ‘t’ mode if you are working with plain-text files and you use \n to delimit your line endings in your script, but expect your files to be readable with applications such as notepad. You should use the ‘b’ in all other cases (Especially working with binary files).
<?php $myFile = fopen('c:\folder\my.png', 'rb'); $myFile2 = fopen('my-file.txt', 'rt'); ?>
If you want to stop your PHP script after failed to open files, you have to use the PHP die() function.
<?php $myNewFile = fopen('new-file2.txt','r') or die("Oops, Failed to open the file."); ?>