php:写文件

时间:2008-11-13 00:08:59

标签: php file-io

我想在PHP中动态地在Web服务器上创建一个文件。

首先,我创建一个存储文件的目录。这个工作

// create the users directory and index page
$dirToCreate = "..".$_SESSION['s_USER_URL'];
mkdir($dirToCreate, 0777, TRUE); // create the directory for the user

现在我想创建一个名为index.php的文件,并将一些内容写入其中。

我在尝试:

$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");
fclose($ourFileHandle);

// append data to it
$ourFileHandle = fopen($ourFileName, 'a') or die("can't write to file");

$stringData = "Hi";

fwrite($ourFileHandle, $stringData);

但它永远不会超过$ourFileHandle = fopen($ourFileName, 'x') or die("can't open file");说文件不存在,但这就是重点。我想创建它。

我做了一些回应,路径(/ people / jason)存在,我正在写信给/people/jason/index.php

有没有人对我做错了什么有任何想法?

我相信Linux服务器上的PHP 5。

-Jason

5 个答案:

答案 0 :(得分:5)

首先你做:

$dirToCreate = "..".$_SESSION['s_USER_URL']; 

但是您尝试写入的文件名不以“..”为前缀,因此请尝试更改

$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";

$ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php';

或者可能更整洁:

$ourFileName = $dirToCreate . '/index.php';

您可能收到警告,因为您尝试将文件写入的目录不存在

答案 1 :(得分:0)

这可能是您的一个php ini设置,或者可能是apache安全设置的结果。

尝试仅将rir创建为rwxr-x ---并查看其结果。

我记得一个共享主机设置,其中编译了“safemode”并且这种行为倾向于发生,基本上,如果文件/目录可由太多人写入,他们将神奇地停止访问。

它可能在php中说过,但是不得不检查。

答案 2 :(得分:0)

为什么不使用:

file_put_contents( $filename, $content )

或者您可以在写入之前touch文件。

答案 3 :(得分:0)

文件'index.php'是否已经存在?使用'x'模式时,如果文件存在,fopen将返回FALSE并触发警告。

答案 4 :(得分:0)

我首先注意到的是你在树中创建一个更高的目录,然后尝试在当前文件夹中创建php文件。如果我错了,请纠正我,但你不是想在新创建的文件夹中创建文件吗?如果我正确地回忆起PHP(请原谅我已经有一段时间了,我可能会在这里添加一些来自另一种语言的东西没有注意到)这里对初学者来说是一种更容易理解的方式,当然更改相应的值,这只是制作一个目录然后创建一个文件然后设置权限。

<?php

$path = "..".$_SESSION['s_USER_URL'];   
// may want to add a tilde (~) to user directory
// path, unixy thing to do ;D

mkdir($path, 0777); // make directory, set perms.

$file = "index.php"; // declare a file name

/* here you could use the chdir() command, if you wanted to go to the 
directory where you created the file, this will help you understand the 
rest of your code as you will have to perform less concatenation on
 directories such as below */

$handle = fopen($path."/".$file, 'w') or die("can't open file");
// open file for writing, create if it doesn't exist

$info = "Stack Overflow was here!";  // string to input

fwrite($handle, $info);   // perform the write operation

fclose($handle);  // close the handle

?>
相关问题