How do I create file on server?

前端 未结 5 960
情深已故
情深已故 2021-01-03 11:22

Let say I want create file call style.css in /css/ folder.

Example : When I click Save button script will create style.css with content

相关标签:
5条回答
  • 2021-01-03 11:41

    You can use the is_writable function to check whether the file is writable or not.

    For example:

    <?php
    $filename = '/path/to/css/style.css';
    if (is_writable($filename)) {
        echo 'The file is writable';
    } else {
        echo 'Please chmod 777 to /css/ folder';
    }
    ?>
    
    0 讨论(0)
  • 2021-01-03 12:00

    fopen with 'w' flag

    0 讨论(0)
  • 2021-01-03 12:01
    $data = "body {background:#fff;}
    a {color:#333; text-decoration:none; }";
    
    if (false === file_put_contents('/css/style.css', $data))
       echo 'Please chmod 777 to /css/ folder';
    
    0 讨论(0)
  • 2021-01-03 12:04

    is the function you may want to use

    • http://php.net/manual/en/function.fopen.php to open the file
    • http://php.net/manual/en/function.fwrite.php to write your css
    • http://php.net/manual/en/function.fclose.php to close the file

    or use

    • http://php.net/manual/en/function.file-put-contents.php just one command to master them all

    if you fopen the file and the result of the operation is false then you can't write the file (maybe for permissions, maybe for UID mismatch in safe mode)

    file_put_contents (php5 and upper) php calls fopen(), fwrite() and fclose() for you and return false if something id wrong (you should make yourself sure that false is really the boolean value though).

    0 讨论(0)
  • 2021-01-03 12:04
    <?php
    $filename = 'test.txt';
    $somecontent = "Add this to the file\n";
    
    // Let's make sure the file exists and is writable first.
    if (is_writable($filename)) {
    
        // In our example we're opening $filename in append mode.
        // The file pointer is at the bottom of the file hence
        // that's where $somecontent will go when we fwrite() it.
        if (!$handle = fopen($filename, 'a')) {
             echo "Cannot open file ($filename)";
             exit;
        }
    
        // Write $somecontent to our opened file.
        if (fwrite($handle, $somecontent) === FALSE) {
            echo "Cannot write to file ($filename)";
            exit;
        }
    
        echo "Success, wrote ($somecontent) to file ($filename)";
    
        fclose($handle);
    
    } else {
        echo "The file $filename is not writable";
    }
    ?>
    

    http://php.net/manual/en/function.fwrite.php | Example 1

    0 讨论(0)
提交回复
热议问题