How to create a file on the server?

Let's say I want to create a style.css call file in a folder /css/.

Example: When I click the "Save" button, the script will create style.csswith content

 body {background:#fff;}
 a {color:#333; text-decoration:none; }

If the server cannot write the file, I want to show an error message Please chmod 777 to /css/ folder

Tell me

+3
source share
5 answers
$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';
+6
source

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

For instance:

<?php
$filename = '/path/to/css/style.css';
if (is_writable($filename)) {
    echo 'The file is writable';
} else {
    echo 'Please chmod 777 to /css/ folder';
}
?>
+4
source

- ,

if you open the file and the result of the operation is false, you cannot write the file (perhaps for permissions, perhaps for UID mismatch in safe mode)

file_put_contents (php5 and upper) php calls fopen (), fwrite () and fclose () for you and returns false if something is wrong (you should make sure that false is indeed a boolean value, though).

+1
source

fopen with 'w' flag

0
source
<?php
$filename = 'test.txt';
$somecontent = "Add this to the file\n";

// Let 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 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
source

Source: https://habr.com/ru/post/1795066/


All Articles