- PHP File Handling
- File Opening in PHP
- File Reading in PHP
- Reading a File Line by Line
- File Writing in PHP
- Closing a File in PHP
- fopen
- Parameters
- PHP File Open/Read/Close
- PHP Open File — fopen()
- Example
- PHP Read File — fread()
- PHP Close File — fclose()
- PHP Read Single Line — fgets()
- Example
- PHP Check End-Of-File — feof()
- Example
- PHP Read Single Character — fgetc()
- Example
- Complete PHP Filesystem Reference
- Open file and load text using php
- Open file and load text using php
PHP File Handling
PHP supports file handling which is used to read, write and append data to the file.
File Opening in PHP
If an attempt to open a file fails then fopen returns a false value, otherwise it returns a file pointer which is used for further reading or writing of that file.
File Reading in PHP
Once a file is opened using fopen() function then it can be read by a function called fread(). This function requires two arguments. The file pointer and length in bytes of the file must be expressed.
The files size can be calculated using the filesize() function which takes the file name as its argument and returns the size of the file in bytes.
$fileSize = filesize( $fileName ); $fileData = fread( $fp, $fileSize ); ?>
Reading a File Line by Line
The fgets() function is used to read a single line from a file, and after a call to this function, the file pointer has moved to the next line.
File Writing in PHP
Using the PHP fwrite() function, a new file can be written, or text can be appended to an existing file. This function requires two arguments, first specifying a file pointer and the string of data that is to be written. Optionally a third integer argument can be used to specify the length of the data to write. If the third argument is used, file writing will stop after the specified length has been reached.
fwrite( $fp, "This is a sample text to write\n" ); ?>
Closing a File in PHP
In PHP it is not system critical to close all your files after using them because the file will auto close after PHP code finishes execution.
You can close file, using fclose() function.
//some code to be executed fclose( $fp ); ?>
The fclose() function requires a file pointer as its argument and then returns true when the closure succeeds or false if it fails.
fopen
fopen() binds a named resource, specified by filename , to a stream.
Parameters
If filename is of the form «scheme://. «, it is assumed to be a URL and PHP will search for a protocol handler (also known as a wrapper) for that scheme. If no wrappers for that protocol are registered, PHP will emit a notice to help you track potential problems in your script and then continue as though filename specifies a regular file.
If PHP has decided that filename specifies a local file, then it will try to open a stream on that file. The file must be accessible to PHP, so you need to ensure that the file access permissions allow this access. If you have enabled open_basedir further restrictions may apply.
If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.
Note:
The list of supported protocols can be found in Supported Protocols and Wrappers. Some protocols (also referred to as wrappers ) support context and/or php.ini options. Refer to the specific page for the protocol in use for a list of options which can be set. (e.g. php.ini value user_agent used by the http wrapper).
On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.
The mode parameter specifies the type of access you require to the stream. It may be any of the following:
mode | Description |
---|---|
‘r’ | Open for reading only; place the file pointer at the beginning of the file. |
‘r+’ | Open for reading and writing; place the file pointer at the beginning of the file. |
‘w’ | Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it. |
‘w+’ | Open for reading and writing; otherwise it has the same behavior as ‘w’ . |
‘a’ | Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() has no effect, writes are always appended. |
‘a+’ | Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended. |
‘x’ | Create and open for writing only; place the file pointer at the beginning of the file. If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING . If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call. |
‘x+’ | Create and open for reading and writing; otherwise it has the same behavior as ‘x’ . |
‘c’ | Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to ‘w’ ), nor the call to this function fails (as is the case with ‘x’ ). The file pointer is positioned on the beginning of the file. This may be useful if it’s desired to get an advisory lock (see flock() ) before attempting to modify the file, as using ‘w’ could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested). |
‘c+’ | Open the file for reading and writing; otherwise it has the same behavior as ‘c’ . |
‘e’ | Set close-on-exec flag on the opened file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems. |
Note:
Different operating system families have 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) for your operating system. Unix based systems use \n as the line ending character, Windows based systems use \r\n as the line ending characters and Macintosh based systems (Mac OS Classic) used \r as the line ending character.
If you use the wrong line ending characters when writing your files, you might find that other applications that open those files will «look funny».
Windows offers a text-mode translation flag ( ‘t’ ) which 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 ‘b’ or ‘t’ as the last character of the mode parameter.
The default translation mode is ‘b’ . You can 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 old versions of notepad. You should use the ‘b’ in all other cases.
If you specify the ‘t’ flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.
Note:
For portability, it is also strongly recommended that you re-write code that uses or relies upon the ‘t’ mode so that it uses the correct line endings and ‘b’ mode instead.
Note: The mode is ignored for php://output , php://input , php://stdin , php://stdout , php://stderr and php://fd stream wrappers.
The optional third use_include_path parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.
PHP File Open/Read/Close
In this chapter we will teach you how to open, read, and close a file on the server.
PHP Open File — fopen()
A better method to open files is with the fopen() function. This function gives you more options than the readfile() function.
We will use the text file, «webdictionary.txt», during the lessons:
AJAX = Asynchronous JavaScript and XML
CSS = Cascading Style Sheets
HTML = Hyper Text Markup Language
PHP = PHP Hypertext Preprocessor
SQL = Structured Query Language
SVG = Scalable Vector Graphics
XML = EXtensible Markup Language
The first parameter of fopen() contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened. The following example also generates a message if the fopen() function is unable to open the specified file:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fread($myfile,filesize(«webdictionary.txt»));
fclose($myfile);
?>?php
Tip: The fread() and the fclose() functions will be explained below.
The file may be opened in one of the following modes:
Modes | Description |
---|---|
r | Open a file for read only. File pointer starts at the beginning of the file |
w | Open a file for write only. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a | Open a file for write only. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x | Creates a new file for write only. Returns FALSE and an error if file already exists |
r+ | Open a file for read/write. File pointer starts at the beginning of the file |
w+ | Open a file for read/write. Erases the contents of the file or creates a new file if it doesn’t exist. File pointer starts at the beginning of the file |
a+ | Open a file for read/write. The existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist |
x+ | Creates a new file for read/write. Returns FALSE and an error if file already exists |
PHP Read File — fread()
The fread() function reads from an open file.
The first parameter of fread() contains the name of the file to read from and the second parameter specifies the maximum number of bytes to read.
The following PHP code reads the «webdictionary.txt» file to the end:
PHP Close File — fclose()
The fclose() function is used to close an open file.
It’s a good programming practice to close all files after you have finished with them. You don’t want an open file running around on your server taking up resources!
The fclose() requires the name of the file (or a variable that holds the filename) we want to close:
PHP Read Single Line — fgets()
The fgets() function is used to read a single line from a file.
The example below outputs the first line of the «webdictionary.txt» file:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
echo fgets($myfile);
fclose($myfile);
?>?php
Note: After a call to the fgets() function, the file pointer has moved to the next line.
PHP Check End-Of-File — feof()
The feof() function checks if the «end-of-file» (EOF) has been reached.
The feof() function is useful for looping through data of unknown length.
The example below reads the «webdictionary.txt» file line by line, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one line until end-of-file
while(!feof($myfile)) echo fgets($myfile) . «
«;
>
fclose($myfile);
?>?php
PHP Read Single Character — fgetc()
The fgetc() function is used to read a single character from a file.
The example below reads the «webdictionary.txt» file character by character, until end-of-file is reached:
Example
$myfile = fopen(«webdictionary.txt», «r») or die(«Unable to open file!»);
// Output one character until end-of-file
while(!feof($myfile)) echo fgetc($myfile);
>
fclose($myfile);
?>?php
Note: After a call to the fgetc() function, the file pointer moves to the next character.
Complete PHP Filesystem Reference
For a complete reference of filesystem functions, go to our complete PHP Filesystem Reference.
Open file and load text using php
How can i make file writing process finish before moving ahead? // writing to file // writing to the file Solution 1: The reason it does not work is because when you are done writing a string to the file the file pointer points to the end of the file so later when you try to read the same file with the same file pointer there is nothing more to read. . HTML : PHP codes : And i put All of them in the body Solution: use file_get_contents() function to read content of file like below set file content in textarea Question: I am trying to write to a file and then read the data from the same file.
Open file and load text using php
I’m writing code and found a problem in taking data from file using php. So the goal is to take information from txt file and create div blocs. SO here I have on problem and one question, I hope that you can help me with that.
So here is a problem — I open a file and start reading but some how it is continue reading file even if it is empty. It is can not stop.
So I planing have a file with a lot of strings but it can not stop reading even an empty file, Please help me to find a mistake. Also in while I planing to create a new block div . so here is a new question- how is better to create a div block? I use printf like that —
But the problem is that the block will be a complex and plus it suppose to be a php function inside the block to put the information inside from database to that block. So can u recommend other methods to realize it?
Use foreach, Luke! And also file_get_contents and explode .
Note how I called trim() inside . Poof, PHP inside HTML!