How to Create, Edit and Delete File using PHP

0

PHP is a very powerful scripting language. Using PHP, you can perform various file operations. In this tutorial, I will show you how you can create, read, edit and delete file using PHP. You may also like How to Add, Edit and Delete Records Using jQuery, Ajax, PHP and MySQL and How to Delete Multiple Records From MySQL Using PHP.

HTML Code

<html>
    <body>

        <form method="post" action="" >
            <input type="text" name="file_name">
            <input type="submit" value="Create File" name="create_file">
        </form>

        <form method="post" action="" >
            <input type="text" name="file_name">
            <textarea name="edit_text"></textarea>
            <input type="submit" value="Edit File" name="edit_file">
        </form>

        <form method="post" action="" >
            <input type="text" name="file_name">
            <input type="submit" value="Delete File" name="delete_file">
        </form>

    </body>
</html>

PHP Code

<?php
if (isset($_POST['create_file'])) {
    $file_name = $_POST['file_name'];
    $folder = "";
    $ext = ".txt";
    $file_name = $folder . "" . $file_name . "" . $ext;
    $create_file = fopen($file_name, 'w');
    fclose($create_file);
}

if (isset($_POST['edit_file'])) {
    $file_name = $_POST['file_name'];
    $write_text = $_POST['edit_text'];
    $folder = "";
    $ext = ".txt";
    $file_name = $folder . "" . $file_name . "" . $ext;
    $edit_file = fopen($file_name, 'w');

    fwrite($edit_file, $write_text);
    fclose($edit_file);
}

if (isset($_POST['delete_file'])) {
    $file_name = $_POST['file_name'];
    $folder = "";
    $ext = ".txt";
    $file_name = $folder . "" . $file_name . "" . $ext;
    unlink($file_name);
}
?>