Php file read only

PHP Basic File Handling Tutorial

In this tutorial we learn how to work with external files such as csv, or txt. We cover how to open, read, write to, close and delete files in PHP.

What is file handling?

When developing a web application, we may often need to work with external files such as .txt, .csv etc. PHP provides pre-defined functions for these file handling operations to make it easier and faster to handle files and the data inside them.

The table below shows the functions available for file handling:

Function Description
fopen() Open/Create a file
fread() Read a file
fwrite() Write/Append to a file
fclose() Close a file
unlink() Delete a file

How to create a new file

The fopen() function is responsible for opening a file, but if the file does not exist PHP will create the file for us.

 The fopen() function requires a mode that tells PHP what to do when creating the file. The following table shows the available modes:
Mode Description
r Open a file with read only privileges. The pointer starts at the beginning of the file.
w Open a file with write only privileges. If the file does not exist, create it. If the file exists, erase the contents. The pointer starts at the beginning of the file.
a Open a file with write only privileges. If the file does not exist, create it. If the file exists, preserve existing data. The pointer starts at the end of the file.
x Creates a new file with write only privileges. If the file exists, return false and raise an error.
r+ Open a file with read/write privileges. The pointer starts at the beginning of the file.
w+ Open a file with read/write privileges. If the file does not exist, create it. If the file exists, erase the contents. The pointer starts at the beginning of the file.
a+ Open a file with read/write privileges. If the file does not exist, create it. If the file exists, preserve existing data. The pointer starts at the end of the file.
x+ Creates a new file with read/write privileges. If the file exists, return false and raise an error.

We also tell the interpreter to stop execution if the file operation is unsuccessful with the die() function.

When we run the example above, a file calle file.txt is created in our PHPProjects directory.

How to write to a file

Now that the file has been created, we can write data to it with the fwrite() function.

 Before writing to a file we must open the file with the appropriate mode for writing privileges. The fopen() function returns the resource id that we need to reference.
In the example above, we use the resource id returned from the fopen() function as the file to write to. We also open the file with mode a so that existing data inside the file is preserved and we don’t overwrite anything. Essentially we’re appending to the file.

When we open file.txt, we can see that the list of movies has been written to it successfully.

In a real world situation it’s more likely that the data will be in an array, in which case we can use a loop to write the data to the file.

When we run the example above, it will add all the items in the array to our file.txt which we can confirm by opening the file.
Best movies of all time: 1. The Godfather 2. Star Wars: Episode V 3. The Dark Knight 4. Pulp Fiction 5. Back To The Future 6. Alien 7. Fight Club 8. Die Hard 9. Jurassic Park 10. Inception

How to read from a file

PHP provides us with two main options to read a file:

  • readfile(): reads the entire file.
  • fread(): reads only a specific amount of bytes.

Read a file with readfile()

When we just want to read the whole file into the output buffer, we use the readfile() function.

In this case we don’t need to open the file beforehand because the readfile() function will do it for us.

 The readfile() function only outputs the file to the output buffer. If we want to see it on the webpage, we will need to print it.
When we run the example above, we can see that everything inside file.txt is printed to the browser.

You may have noticed though that everything is on one line instead of multiple lines, as we defined in the file.

PHP preserves the linebreaks (\n) in the output, but in HTML the whitespace is collapsed by default. If we want to preserve it, we can use the whitespace CSS attribute.

When we run the example above, the linebreaks will be respected and the output will look similar to the actual text file.

Read a file with fread()

We can use the fread() function to read the entire file or just a specific amount of bytes.

The fread() function needs a resource id as its first parameter so we need to open the file beforehand.

 If the file is a document that contains text, 1 byte is equivalent to 1 character.
When we run the example above, it prints out the first 23 bytes (Best movies of all time) to the page.

To read the whole file with the fread() function, we need to calculate its size and use that size for the length parameter.

PHP provides us with the filesize() function to calculate the size of a file.

 Example: read the whole file with fread()
In the example above, we again wrap the output in a div that preserves the linebreaks.

Read a file line by line with fgets()

PHP provides us with the fgets() function to read the contents of a file until it reaches the newline character (\n).

The fgets() function needs a resource id so the file must be opened beforehand.

 Example: main.php - read the file line by line
  When we run the example above it will print out the first two lines of file.txt.

We can also read the whole file this way within a loop by evaluating if the pointer is at the end of the file. The feof() function can be used to return true if the pointer is at the end of the file.

It’s good practice to close a file after using it so that the resources connected to it can be released. In PHP the fclose() function is used to close files.

Источник

PHP fopen() Function Tutorial

PHP fopen() Function Tutorial

PHP provides the fopen() function in order to open files. Even fopen() is created to open files it can also open different types of resources and protocols like HTTP, HTTPS, FTP, etc. Opening a file seem simple operation but it may have different file open modes like a read-write, read-only, open file if not exit create, etc. fopen() is derived from the C programming language, and most of the attributes are derived from C.

fopen() Function Syntax

fopen() function has the following syntax. Even there are 4 parameters in general two parameters are used where these are required to call fopen() function.

fopen( $filename , $mode , $use_include_path , $context)
  • $filename is the most important parameter where the file, URL, or similar name and scheme is provided to open. $file parameter is required.
  • $mode parameter is another required parameter where the file or resource open mode is specified. The file can be opened read-only, read/write, etc. File open modes are explained in detail below.
  • $use_include_path is an optional parameter a rarely used.
  • $context is an optional parameter rarely used.

File Open Modes

fopen() function can be used to open files in different modes. The $mode parameter is the second parameter of the fopen() function and required to open a file. Below we will list all possible modes for the fopen() function. The mode parameter is provided as a string in single or double-quotes.

‘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; 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.
‘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’ .

PHP fopen() Function File Open Modes

Open File with fopen() Function

We will start with a simple example where we will open file in different ways. We will open file with its absolute path, relative path, Windows file etc.

Open File Read-Only with fopen() Function

Files can be opened for different operations with diffrent modes. But the read-only mode is one of the most popular mode where the content of the opened files can read but can not be edited. We will explicitly provides examples about opening a file in read-only mode for Linux and Windows operating systems with absolute and relative paths.

Open File and Create If Do Not Exist with fopen() Function

Another popular case with an opening file in PHP is trying to open a file and if the file does not exist create and open a file to write. The w+ mode can be used to open a file for writing and if does not exist create and open for writing.

Open Web Page (HTTP) with fopen() Function

Even the fopen() function is created for opening files residing on disks and file system later it gained extra features like opening web pages or HTTP or HTTPS protocol. In order to open a web page the URI scheme should be provided with will be http or https and then the complete or absolute path should be provided. We will use the mode as “r” as we can not change the provided URI or web page.

Open FTP with fopen() Function

FTP or File Transmission Protocol is another popular internet protocol that is used to transfer files over the internet or service via FTP services. The fopen() method can be used to open FTP URI like below. If the remote FTP requires authentication with a username and password we can provide the username and password via the FTP URI. We can use “r” and “w” modes where we can read and write files on the FTP server.

Open Directory with fopen() Function

Can we open directory with fopen()? Yes, even the fopen() is designed to open files it can also open directories as from the Linux filesystem point of view everything on the system is a file. A directory is a file too and can be opened with the fopen() function.

Close Opened File with fclose() Function

Opening files will lock the opened file and take some system resource to work on file. In order to complete opened file operation properly the file should be closed with the fclose() function. Also closing file properly will make changes or any write persistent on the file.

Источник

Читайте также:  Java апплет для firefox
Оцените статью