Unknown Error
Unknown Error

Reputation: 797

How do I create file on server?

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

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

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

Let me know

Upvotes: 3

Views: 10619

Answers (5)

Thew
Thew

Reputation: 15959

<?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

Upvotes: 0

Eineki
Eineki

Reputation: 14909

is the function you may want to use

or use

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).

Upvotes: 1

linepogl
linepogl

Reputation: 9335

$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';

Upvotes: 6

usoban
usoban

Reputation: 5478

fopen with 'w' flag

Upvotes: 0

Luca Matteis
Luca Matteis

Reputation: 29267

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';
}
?>

Upvotes: 4

Related Questions