Thursday, June 4, 2009

PHP - File Create

Using the PHP file system function fopen(), we can create a new file

The function fopen() takes in two arguments, the filename and the mode to either open or create a file.

  • $filename - the name of the file. This may also include the absolute path where you want to create the file. Example, "/www/myapp/myfile.txt".
  • $mode - mode is used to specify how you want to create the file. For example, you can set the mode to create for read only, or create a file for read and write.
Example:

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

  1. $ourFileName = "testFile.txt";

    The name of our file is "testFile.txt" and it is stored into a String variable $ourFileName.

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

    We use the function fopen and give it two arguments: our file name and we inform PHP that we want to write by passing the character "w".

  3. fclose($ourFileHandle);

    We close the file that was opened. fclose takes the file handle that is to be closed.