PHP - Creating and Writing to a File

Accessing and Editing Files with PHP

If you are working with PHP, chances are that you will eventually need to create and save data to a file on the web server.

The PHP command you need is fopen();

There are a variety of arguments to use with fopen(), but for our purposes we will use the following line of code:

$file_handle = fopen($file_name, 'w') or die("PHP could not open the file!");

 
  • $file_handle holds the value returned by fopen(), and will be needed later when writing to the file;
  • $file_name is the name of the file that you want to create or write to;
  • 'w' means "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.";
  • if fopen() fails, die() displays the quoted error text;

You can write the contents of a variable to the file like this:

$one_line = "This text is the FIRST line in the file.\n";

fwrite($file_handle, $one_line);

  • The first line above passes content into the variable $one_line;
  • The second line uses fwrite() to write the contents of $one_line to the file, using the variable $file_handle to indicate which file;
  • The \n at the end of the string¬†indicates that you want to add a line break to the file;¬†

You can continue writing to the file like this:

$one_line = "This text is the SECOND line in the file.\n";

fwrite($file_handle, $one_line);

When you are done working with the file, you have to close it, using fclose():

fclose($file_handle);

PHP Sample Code for Creating and Writing to a File

Here is the full PHP code from above, without the comments:

$file_handle = fopen($file_name, 'w') or die("PHP could not open the file!");

$one_line = "This text is the FIRST line in the file.\n";

fwrite($file_handle, $one_line);

$one_line = " This text is the FIRST line in the file.\n";

fwrite($file_handle, $one_line);

fclose($file_handle);

More by this Author


Comments

No comments yet.

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working