Enter your Sign on user name and password.

Forgot password?
Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Advanced PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for Educator.com

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

Writing to Files

  • fwrite() is used to write the contents of a string to a file that has been opened for writing. It has an alias: fputs().
  • In order to write to a file with fwrite(), an access mode specifier allowing writing must be provided to fopen() when opening the file to be written to.
  • Two commonly used write access mode specifiers are:
    • 'a' (append) - open for writing only; place file pointer at the end of the file; attempt to create file if it does not exist
    • ‘w’ (overwrite) – open for writing only; delete file contents; place file pointer at beginning of file; attempt to create file if it does not exist
  • Additional Resources:

Writing to Files

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Lesson Overview 0:09
    • Lesson Overview
  • Review of File I/O 0:40
    • Review of File I/O
  • fwrite() 1:38
    • fwrite()
    • fputs()
    • 'r+'
    • Coding Example: fwrite()
  • fopen() Access Modes 8:41
    • 'a' and 'a+'
    • 'w' and 'w+'
  • Homework Challenge 14:47
    • Homework Challenge

Transcription: Writing to Files

Hello again, and welcome back to Educator.com's Advanced PHP with MySQL course.0000

In today's lesson, we are going to be covering the topic of writing to files.0005

Our lesson is going to start with a review of how file I/O works, and the steps that are involved in that.0011

And we had gone over that previously, in our lesson that introduced us to reading from files.0016

We are going to go over a key method called fwrite, which is a method that is built into PHP that allows us to write data to files.0021

And then, we are going to talk about different access modes that you can use0028

with the fopen function to open a file for writing in different ways; and we are going to learn about that.0032

We learned in our lecture on reading from files that, when you perform I/O on a file, it has three steps.0042

You open the file; you perform your read or write operations; and then you close the file.0050

For writing the files, our steps are: we are going to open the file, and then0055

we are going to perform write operations on it, and then we are going to close the file.0060

This step is obviously going to differ, because now, instead of reading, we are going to be writing to the file.0065

The third step is still going to be the same, though: it is just going to be using the fclose method to close an open file.0070

Step 1 will be a little different, and that is because we are going to have to pass0077

a different access mode parameter to the fopen method in order to be able to write to the files.0079

In order to open a file for writing, it requires a different access mode specifier0088

than what we had used in our reading examples, which was just the lowercase r letter.0092

Before I talk more about the access modes, I want to talk about the fwrite function.0100

The fwrite function is used to write the contents of a string to an open file,0105

in a file that is opened with an access mode that allows it to be written to.0111

It takes a file handle to an open file as one of its parameters.0116

And then, as a second parameter, it takes a string; and wherever the file pointer is for that currently-open file,0121

it is going to write the contents of that string wherever that file pointer is currently located at.0131

If it is successful, it returns the number of bytes that it was able to write; and if an error occurs, it returns false.0135

One thing to note is that you may also see the function fputs used.0141

That is an alias of fwrite that does the same exact thing; in this course, we are just going to use the fwrite method.0145

And so, we have a slide where we are going to talk about the access modes; but just to get us started with using fwrite:0153

to open an existing file for reading or writing (and this is going to open the file), we use the r+ access mode specifier.0160

What that is going to do is allow us to open a file for reading and writing, which is where the + sign comes from.0171

And it is going to place the file pointer at the beginning of the file.0176

If we go and take a look for a script that we have written for this lecture, called fwrite.php,0180

What we have done is: we define a string to a data text file that we want to write to.0185

In this case, it is located in the data subdirectory of where this script is located, and it is going to be called data.txt.0192

And then, we are going to create a string that we want to write to the file.0200

In this case, we are going to be creating a string that says, "File is written to at" and it is going to0204

use the date function to just dynamically generate a date, and then output a new line character.0208

So, what is going to happen is: when we write this string to the file, it is going to output "File written to at" with the date.0215

And then, it is going to add a new line; so it is going to put the file pointer at the beginning of the next line.0220

And the reason I have gone ahead and used that date function is so that, rather than using a static value,0227

we can see that, each time we write, it is going to write a different value.0233

So then, what we do is use our fopen method, as we had before, for reading a file, except now we are using this r+ modifier,0238

which, again, opens the file for reading or writing; and it places the file pointer at the beginning of the file.0245

And then, we simply use the fwrite method that we just learned about.0252

We pass it the file handle to this open file, and then we pass it this string variable,0255

which has this date string up here; and we check the result written.0259

And if it was successful, written is going to contain the number of bytes that were written.0264

If it is unsuccessful, it is going to return false.0269

And so, we have a little error checking down here that will output the number of bytes written if it was successful.0272

Otherwise, it will say, "There was an error writing to the file."0277

And then, down here, you can see, we have our fclose method, which is what we use to close a file.0280

And that is the same function call we had used before.0284

Let's go take a look at trying to load this file.0289

Here, if we load fwrite.php...0294

And we can see, also (just so you know), that if we have a blank file called data.txt that is in0297

this data directory of the lecture 7 directory (so it is a subdirectory of where the fwrite.php file is),0302

right now it is a blank file, and if we go ahead and run the script fwrite.php, it is going to say, "41 bytes were successfully written to the file."0310

And it has a link that we created down here to view the text file.0324

And when we view data.txt, we can see, "The file was written to at 4:26 and one second on August 5, 2011."0328

You can see how we were able to open up the file and write to it; and we wrote from the beginning of the file.0338

Now, as mentioned, one thing that you can use--one alternative to using fwrite that you might see--is fputs.0344

So, we can use the fputs method as well, and it is going to do the same thing.0353

If we note the time of the file (4:26:01) and we go ahead and refresh this page (which is going to write again to that file),0358

and we view the text file again, now it is 4:26 and 48 seconds.0367

So, it has gone ahead and updated it; fputs worked the same way.0371

And one thing to note, as you can see, is that this file only has one line,0375

even though we have written to it twice--we have written to the same file--0379

because what happens is: the fwrite function writes its output to wherever the current file pointer is on the file handle that you pass to it.0382

In this case...when we open the file using the r+ access modifier, the file pointer is always at the beginning.0391

So, in this case, we are always going to output our date string at the very beginning of the file.0397

And in this case, it is just going to overwrite the last one.0403

And one of the ways you can see that is if we go ahead and change our string.0405

So, right now, our data text file has this line here: File written to at 4:26 and 48 seconds.0413

Now, if we change our string that we are going to write, and just have some static string (for example, 1234--a 4-character string),0422

we are going to see how the fwrite just overwrites whatever characters are at the current position of the file pointer.0432

For example, when we call this, after we open the file, our r+ access modifier is going to put the file pointer at the beginning of the file.0443

When we call fputs or fwrite to write this 4-character string, it is just going to overwrite the first four characters in that file.0452

For example, if we go ahead and reload this page again, now it is going to say0459

"4 bytes were written to the file," meaning that this string was only length 4.0464

And if we view our data file, we can see that what it did was overwrite the first four letters of the text file previously there: 1234.0467

That is something just to note about the way fwrite and fputs work.0477

One other thing to notice is that, with the r+ modifier, you are going to get an error if you try to open a file that doesn't exist.0482

For example, this file data1.txt doesn't exist.0494

So, when we try to write to it, if we reload the script, we are going to get an error saying "You are trying to open a file that doesn't exist."0497

And so, when you use the r+ access modifier, it won't create a file automatically.0508

We are going to see in a minute that using other access modifiers will allow a file to be created automatically,0513

if it is not available when you try to open it.0517

Let's take a look at the different access modes available to fopen.0523

A subset of the different access mode modifiers (and these are the ones0528

that we are going to use in this course), primarily, is the a access modifier.0532

And that is a modifier that opens the file in append mode.0537

What it does is open the file for writing only, and you place the file pointer at the end of the file.0542

If you have a file that already contains information in it, whatever the next fwrite is0549

that you perform on that file, it is going to add it to the end of the file.0555

One thing to note about this method is that it will attempt to create the file if that file does not exist.0558

An alternate version of the append one is a+, and that allows you to read or write from a file.0565

But as far as opening the file, it does the same thing: it places the file pointer at the end of the file, and it will attempt to create the file.0571

We have a script called appendMode.php; it is going to attempt to open a new data file called dataAppend.txt.0578

It is going to write the same string to it as we had done before; it is this this dynamically-generated date string.0589

The difference here is that, when we call fopen, we specify that a access mode,0596

which is going to say, "Put the file pointer at the end of the file."0603

And then, when we go ahead and write our string, it is going to write at the current location of the file pointer,0610

which, when we first open it, is at the end of the file.0614

So, if we were to call the script multiple times, every time we call it, the file pointer is going to be moved to the end,0617

and it is going to write out this string up here.0622

So, we are actually going to get multiple lines in the file.0626

And down here, this is the same sort of output message that we had before.0628

If we look at our data directory, we can see that there is no dataAppend.txt file.0633

If we go ahead and run this script, appendMode.php, we are going to say that 41 bytes were successfully written in the file.0639

And if we look back at data, we can see that it created the file, which we had mentioned (the append mode will do that).0647

And if we go and open this file, we can see (well, you can do it in the web browser--if we view it) that the file was written to at 4:31 and 27 seconds.0655

Now, because it opens in append mode, it sets the file pointer at the beginning.0669

If we run this script again, it is going to add a new line that contains a new date.0672

So, if we go ahead and refresh the page (and actually, I am going to do it a couple of times),0678

on each refresh, it is going to open the file and write a string to it.0682

Now, if we click View dataAppend.txt again, you can see that multiple lines were added to it, because they have appended it to the end of the file.0685

An alternative to writing a file is what is known as the overwrite access mode, which is specified by w.0695

The w access mode says, "Open the file for writing only; put the file pointer at the beginning of the file; and erase all of the contents of the file."0701

And it will also attempt to create a file if it doesn't exist.0709

There is also the w+ access mode specifier, which does the same thing as w, except it also allows you to read from that file.0713

If we go and look at a script called overwriteMode.php, we can see that we are going to try to open a file called dataOverwrite.txt.0725

And again, using the w access mode will create the file if it doesn't exist.0736

And if we look at our data folder, we can see that that data file does not exist.0741

We are going to try to write this same dynamic string to the file.0746

Here, when we call fopen, we use the w access mode, which says "Open in overwrite mode and write only."0749

So, what it is going to do is: any contents that are in the file, it is going to truncate or get rid of.0756

And then, it is going to place the file pointer at the beginning.0761

So, when we call this fwrite method to write our date string on this file opened using the w mode,0764

it is just going to write it at the first line of the file, because it is going to delete all the contents.0771

If we go and run this script, overwriteMode.php, it is going to say, "41 bytes were successfully written."0775

And we can see that dataOverwrite.txt exists, because it created it.0784

And we can see that, for example, in this case, this date string was created at 4 hours, 33 minutes, and 44 seconds.0790

So, 4:33:44--let's remember that.0799

Now, if we go ahead and refresh the page again and view dataOverwrite.txt, it has advanced.0802

It was 4:33:44, I think, before; now, it has been advanced.0808

And what you can see is that, instead of appending this to the end of the file, like we did when we opened the file in append mode,0811

it overwrote the whole file, and just wrote out that one particular new date string.0816

So, every time, in this case, that we run this, it is going to overwrite the whole file and add a new date string.0823

So, if we were to do it again and refresh it, we would get a new date and time string.0828

Now, one thing to note about all of these methods that will create a file for you, if it doesn't exist,0835

is that it is required that, if you try to create a file, the directory you are trying to create the file in actually exists.0842

That is one requirement: the file doesn't have to exist, but the directory does.0849

For example, let's say, in our overwriteMode.php file, instead of creating dataOverwrite.txt0853

in the data directory, we are going to create it in the data1 directory.0864

What is going to happen is: when we load the script now, we are going to get an error saying0868

that it couldn't create that file, because that directory does not exist.0873

So, that is something that you should pay attention to.0879

And it is just something you have to watch out for, with those methods that allow you to create files.0882

For the homework challenge for this lesson, I want you to create a script that is going to open a file called data.txt.0888

And I want you to open the file using fopen with the a access mode.0896

So, as we just learned, that means that the file doesn't actually have to already be created.0900

And then, actually, I would like you to set it up so that it is not already created.0903

And then, I want you to write any random 10-character string to the file, followed by a new line.0907

Open the file; write a 10-character string to it; close the file.0915

Now, run this script several times; and because this is in append mode, that string is going to be written multiple times to that particular file.0919

If you run it a few times, you will have a couple of lines, all with that 10-character string.0928

Now, I want you to alter the script, so that, when it opens the file, it uses the w access mode, and run the script again.0932

Now, when you run it, it is going to delete all the contents of the file and rewrite that one string.0939

And even if you refresh the page over and over, it is still just going to write that one string,0945

because every time that script is run, it deletes all the contents of that file.0949

Then, I want you to modify the script so that the string you are going to be writing is only 5 characters long.0955

It is still going to open that data.txt file that we have been using.0961

Don't append a new line to it, as we have in the string up here.0967

And then, open the file in r+ access mode; and again, that is going to open the file for reading and writing at the beginning of the file.0973

And then, go ahead and write this 5-character string to the file; close the file; and run the script.0981

And when you run the script and look at the contents of the file, you should see that all it has done is overwritten the first 5 characters in the file.0991

Because in step 3 and 4, we overwrote the file to delete it, and we just added one line to it,0999

a 10-character string, as we learned in this lesson, the fwrite method just overwrites1009

whatever characters it needs to, wherever the current file pointer is.1016

And because the r+ access mode opens the file and places the file pointer at the beginning, it is going to overwrite the first five characters.1021

For example, if you had the numbers 0 through 9, and that was your 10-character string,1030

and then you wanted to overwrite the first five with just 5 x's, for example,1038

if you did that here, you would end up with 5 x's, followed by the digits 5, 6, 7, 8, and 9.1043

And so, that will give you practice with some of the different file modes used for writing to files.1048

That ends today's lesson; thank you for watching Educator.com, and I look forward to seeing you next time.1053