How to Create and Open a File with PHP

Configurare noua (How To)

Situatie

In this section, we’ll see how to create and open a file.

When it comes to creating a file, it’s the fopen function which you’ll end up using most of the time. It may seem a bit confusing to use the fopen function to create a file. In fact, the fopen function does two things: it creates a file if it doesn’t exist and also opens it for reading or writing.

Let’s go through the following example to understand how it works.

Solutie

<?php
$file_handle = fopen('C:\Users\flcri\Desktop\Solutii\3\test.txt', 'w');
?>

In the above example, the fopen function will check if the C:\Users\flcri\Desktop\Solutii\3\test.txt file exists, and if it exists, it’ll open it for writing. By supplying 'w' in the second argument, we specify that we will be writing to the file. If the file doesn’t exist, it’ll be created right away. It’s important to note here that the C:\Users\flcri\Desktop\Solutii\3 directory in the above example must be writable by the web server user for the fopen function to be able to create a file.

The first argument of the fopen function is the filename which you want to open. In the above example, we’ve supplied the C:\Users\flcri\Desktop\Solutii\3\test.txt filename in the first argument. Again, it’s important to note that we’ve supplied an absolute path name.

The second argument is the mode, which specifies the type of access you require to the opened file. The fopen function provides different modes you can choose from. For example:

  • use the r mode to open a file for reading
  • the r+ mode for both reading and writing
  • a mode for reading and appending

In our example, we’ve used the w mode, which opens the C:\Users\flcri\Desktop\Solutii\3\test.txt file for writing only.

Tip solutie

Permanent

Voteaza

(4 din 10 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?