如何在服务器上创建文件?

时间:2011-02-27 15:20:02

标签: php

假设我想在/css/文件夹中创建文件调用style.css。

示例:当我单击“保存”按钮时,脚本将创建包含内容的style.css

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

如果服务器无法写入我想要的文件,则显示错误消息Please chmod 777 to /css/ folder

让我知道

5 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:4)

您可以使用is_writable功能检查文件是否可写。

例如:

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

答案 2 :(得分:1)

是您可能想要使用的功能

或使用

如果您打开文件并且操作结果为false,则无法写入文件(可能是权限,可能是安全模式下的UID不匹配)

file_put_contents(php5和upper)php为你调用fopen(),fwrite()和fclose(),如果id错误则返回false(你应该确定false确实是布尔值)。

答案 3 :(得分:0)

带有'w'标志的

fopen

答案 4 :(得分:0)

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