Create and Open File PHP

Create and open file php - In file and directory management, PHP provides more than 70 functions. Some of the main functions associated with file management (create, write, append, and delete), include:
  • Opening and Creating Files
  • Write to File
  • Reading the contents of the file
  • Closes File
Which I will discuss in this article is to create and open files in php, for others I will discuss in the next article.
Opening and Creating Files
fopen ($namafile, $mode);
Information :
$filename is the name of the file to be created, while $mode is the file access mode. Access mode files that can be used are:


Mode
Information
r
Just to read the file, the pointer is at the beginning of the file
r+
To read and write files, the pointer is at the beginning of the file
w
Just to write the file, the contents of the old file is deleted, if the file does not exist then
Will be created
w+
To read and write files, the contents of old files are deleted, if the file does not exist then
Will be created
a
Just to add the file contents, the pointer is at the end of the file, if the file
Not yet created then
a+
To read and add file contents, the pointer is at the end of the file,
If the file does not exist then it is created

To better understand the following I give examples of programs to create and open php files.
Program 1
File Name: file01.php
Description: Program accesses (unlocks) files with r mode.
Open notepad, then type the following php code.
<?php
$filename = "data.txt";
$handle = fopen ($filename, "r");
if (!$handle) {
 echo "<b>File can not be opened or not yet exists</b>";  } else {
 echo "<b>The file successfully opened</b>";  }
fclose($handle);
?>

Create and Open File PHP

Save the code with file01.php name in htdocs folder. To see the result open the browser, type http://localhost/file01.php in the address bar then enter. Then it will look like the following.
Create and Open File PHP
Program view

Program 2
File Name: file02.php
Description: The program accesses (opens) files in w mode.
Type the following php code in notepad.
<?php
$filename = "data.txt";
$handle = fopen ($filename, "w");
if (!$handle) {
 echo "<b>File can not be opened or not yet exists</b>";  } else {
 echo "<b>The file successfully opened</b>";  }
fclose($handle);
?>

Create and Open File PHP

Save the code with file01.php name in htdocs folder. To see the result open the browser, type http://localhost/file01.php in the address bar then enter. Then it will look like the following.
Create and Open File PHP
Program view

That's the tutorial from me about create and open php file.. Hopefully can add our ability in understanding the php programming language. Learn also the article about Date Function in PHP With Example.

Comments