Create a file using PHP


The fopen function needs two important pieces of information to operate correctly. First, we must supply it with the name of the file that we want it to open. Secondly, we must tell the function what we plan on doing with that file (i.e. read from the file, write information, etc).

Since we want to create a file, we must supply a file name and tell PHP that we want to write to the file. Note: We have to tell PHP we are writing to the file, otherwise it will not create a new file.

PHP Code:

$ourFileName = "testFile.txt";
$ourFileHandle = fopen($ourFileName, 'w') or die("can't open file");
fclose($ourFileHandle);

The PHP logo displaying the Handel Gothic font.

The PHP logo displaying the Handel Gothic font. (Photo credit: Wikipedia)

The file “testFile.txt” should be created in the same directory where this PHP code resides. PHP will see that “testFile.txt” does not exist and will create it after running this code. There’s a lot of information in those three lines of code, let’s make sure you understand it.

  1. $ourFileName = “testFile.txt”;Here we create the name of our file, “testFile.txt” and store it into aPHP String variable $ourFileName.
  2. $ourFileHandle = fopen($ourFileName, ‘w’) or die(“can’t open file”);This bit of code actually has two parts. First we use the function fopenand give it two arguments: our file name and we inform PHP that we want to write by passing the character “w”.Second, the fopen function returns what is called a file handle, which will allow us to manipulate the file. We save the file handle into the$ourFileHandle variable. We will talk more about file handles later on.
  3. fclose($ourFileHandle);We close the file that was opened. fclose takes the file handle that is to be closed. We will talk more about this more in the file closing lesson.
Tagged with:
Posted in Mixz Tricks, PHP

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow me on Twitter

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 442 other followers

%d bloggers like this: