Skip to main content

Practical-11

Write a PHP Program for Create, Delete, and Copying file from PHP Script.

Introduction

This tutorial aims to help users new to programming gain an understanding of creating, deleting, and copying files from a PHP Script. To complete the tasks mentioned in this tutorial, users must be familiar with the core concepts of PHP language such as variables, functions, and loops, and of course, an understanding of HTML to be able to create web pages. The tutorial will demonstrate how to perform basic tasks such as creating, deleting, and copying files. Additionally, it will describe how to check for a file�s existence, read the file�s contents, update the file�s content, and much more. With the given methods and examples, users can create a dynamic and powerful web application using PHP scripting language.

Code

<?php

//To create a file
$file = fopen("file.txt","w");

//To write content in the file
fwrite($file,"Hello World");

//To close the file
fclose($file);

//To delete a file
if (file_exists("file.txt")) {
unlink("file.txt");
}

//To copy a file
$file1 = "file.txt";
$file2 = "copy.txt";

copy($file1, $file2);

?>

Output

Hello World
Explanation

The above code snippets demonstrate how to create, delete, and copy a file from a PHP Script. The fopen function is the first step for creating a file. The w parameter indicates the file should be written to. If the fwrite function is used, the given string is written into the file that has just been created. To delete the file, we employ the file_exists function to detect the existence of the file and use unlink to delete the file. To copy a file, we use the copy function and specify both the source and destination of the file.

Get Help