Please note, this is a STATIC archive of website technosmarter.com from 20 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
 

PHP File Operators


PHP: Create File -

The fopen() function is used to create a file in PHP. The example below creates a new file called "testfile.txt". The file will be created in the same directory where the PHP code resides:
If you have thought that the fopen() is used to open the file but also fopen () create a file.


Example

<?php


$my_file = 'testfile.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file); //implicitly creates file
echo "Your file has been created ";
?>


PHP: Open File -

Now we will learn about how to open the file for that we will use the fopen () function and also a txt file (testfile.txt) to open the file.

Example

<?php
$myfile = fopen("testfile.txt", "r") or die("Unable to open file!");
echo fread($myfile,filesize("testfile.txt"));
fclose($myfile);
?>

PHP: Read file-

The fread() function is used to read the file from the directory .
The first parameter of fopen() contains the file name (a variable in which we have stored file ) and the second parameter contains the file size to be read .
In below example we will read the (testfile.txt).

Example


fread($myfile,filesize("testfile.txt"));

PHP: Write to a file .

The fwrite() writes to an file.

Example

<?php
$myfile = fopen("testfile.txt", "w") or die("Unable to open file!");
$txt = "Hello my name is vishal rana ";
fwrite($myfile, $txt);
$txt = "Jane Doen";
fwrite($myfile, $txt);
fclose($myfile);
?>

PHP: Delete A file -

The delete() function is used to delete a file.

Example

<?php
echo delete("testfile.txt");
?>

PHP: Append to a File -

Now we will append to a file.

Example

$my_file = 'testfile.txt';
$handle = fopen($my_file, 'a') or die('Cannot open file:  '.$my_file);
$data = 'New line data (line n 1)';
fwrite($handle, $data);
$new_data = "n".'New line data (line no 2)';
fwrite($handle, $new_data);


PHP: Close a File -

The fclose() function is used to close a file.

Example

$my_file = 'testfile.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
//write some data here
fclose($handle);

Please Share

Recommended Posts:-