Home > Software engineering >  Create a file using a PHP script
Create a file using a PHP script

Time:05-24

A folder and a file in it should be created with a PHP file.

Creating the folder works:

// Check if the folder "example" exists, if not create the required CHMOD with it
if (!is_dir("../example")) {
mkdir("../example", 0755, true);
}

Question: How do you have to proceed, for example, to create a file with CHMOD 777 in the newly created folder?

Many thanks in advance for tips and hints.

CodePudding user response:

$filename = "filename.txt";
$file = "../example" . '/' . $filename;
$data = "";    
file_put_contents($file, $data);
chmod($file, 0777);

file_put_contents will generate the file if none is found at the location.

CodePudding user response:

Here I made a complete functions to simplify your dir creation and file creation, make changes as you needed. ❤

    <?php
    // FUNCTIONS for Create DIR and Create FILE by Ajmal PraveeN (AP)
    function createDir($dir) {
        # Code by Ajmal PraveeN (AP)
        # If there is no dir exists by given file path (rescursively creates folder).
        if ( !is_dir($dir) ) {
            mkdir($dir, 0777, true); # Default will be 0777 permission
            return true;
        }
        else {
            return false;
        }
    }
    
    
    function createFile($file, $data) {
        # Code by Ajmal PraveeN (AP)
        # If there is no file exists by given file path (rescursively) & filename.
        if ( !is_file($file) ) {
            file_put_contents($file, $data); # Change as per your requirements to any file extension, fcopy or file_put_contents or any php default functions.
            #chmod($file, 0777); # If you want to chmod 0777 permission to the file, uncomment this line.
            return true;
        }
        else {
            return false;
        }
    }
    
    // USAGE
    
    # Usage for dir creation with output
    if ( createDir('/home/create_new_dir/') ) {
        # Code by Ajmal PraveeN (AP)
        ?>
        <b>Directory created for the following path <?php echo $dir; ?></b><br>
        <?php
    }
    else {
        ?>
        <b>Directory creation failed or already exists in following path <?php echo $dir; ?></b><br>
        <?php
    }
    
    
    # Usage for file creation with output
# Just I shown an example to create txt file, make changes if needed fcopy etc.. functions.
    if ( createFile('/home/create_new_dir/test_dump.txt', 'Hello World ! Ajmal PraveeN') ) {
        # Code by Ajmal PraveeN (AP)
        ?>
        <b>File created</b><br>
        <?php
    }
    else {
        ?>
        <b>File creation failed or already exists</b><br>
        <?php
    }

If you have any doubt or issue let me know, Thank you

  • Related