PHP Programing language

adplus-dvertising
PHP Creating A file
Previous Home Next

A file is created by use a command and that is also used to open files. It may seem a little confusing, but we'll try to clarify this conundrum.

In PHP the using a function is called fopen. it's function is used to open files. it can also creating a file if it does not find the file specified in the function call. So if you use fopen on a file that does not exist, it will create it, giving that we open the file for writing or appending.

How to Create a File in 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:

<?php
$FileName = "firsttext.txt";
$FileHandle = fopen($FileName, 'A') or die
("can't be write this file");
fclose($FileHandle);
?>

The file "firsttext.txt" should be create in the same directory where this PHP code resides. PHP will see that "firsttext.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.

$FileName = "firsttext.txt";

Here we create the name of our file, "firsttext.txt" and store it into a PHP String variable $FileName.

$FileHandle = fopen($FileName, 'A') or die("can't 
be write this file");

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 $FileHandle variable. We will talk more about file handles later on.

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.

PHP Permissions

If you are trying to get this program to run and you are having errors, you might want to check that you have granted your PHP file access to write information to the hard drive. Setting permissions is most often done with the use of an FTP program to execute a command called CHMOD. Use CHMOD to allow the PHP file to write to disk, thus allowing it to create a file.

In the near future will have a more in-depth tutorial on how to use CHMOD to set file permissions.

Previous Home Next