在PHP中,我试图为注册和添加文件的不同用户创建一个新的数据库类型文件夹。我可以很容易地创建文件并对其进行写入,但由于某种原因,每次我尝试让PHP使用persons-username变量作为路径创建文件夹时,它所做的只是创建一个名为$username的文件夹。
以下是我的代码,它是该部分的基础部分。
<?php
$title = $_POST["title"];
$myFile = "/users/$username/title.txt";
$fh = fopen($myFile, 'w') or die("There was an error in changing your title. <br />");
$stringData = "$titlen";
fwrite($fh, $stringData);
fclose($fh);
$template = $_POST["temp"];
$myFile = "$structure/template.txt";
$fh = fopen($myFile, 'w') or die("There was an error in changing your template. <br />");
$stringData = "$templaten";
fwrite($fh, $stringData);
fclose($fh);
?>
试试这个
<?php
$title = $_POST["title"];
$myFile = "/users/".$username."/title.txt";
$fh = fopen($myFile, 'w') or die("There was an error in changing your title. <br />");
$stringData = $title."n";
fwrite($fh, $stringData);
fclose($fh);
$template = $_POST["temp"];
$myFile = $structure."/template.txt";
$fh = fopen($myFile, 'w') or die("There was an error in changing your template. <br />");
$stringData = $template."n";
fwrite($fh, $stringData);
fclose($fh);
?>
要实现这一点,您确实需要从字符串中取出变量(正如Ben Griffiths所提到的),并检查它是否为空。此外,请确保首先使用mkdir()创建目录(aschuler也提到了这一点)。因此,代码可能看起来像这样,但在不知道$username、$structure、$title和$template来自哪里的情况下,您可能需要稍微修改一下:
<?php
$title = $_POST['title'];
if (trim($username) == '') {
die("No username passed in!");
} else {
$userdir = "/users".$username."/";
mkdir($userdir);
$fh = fopen($userdir."title.txt", 'w') or die("There was an error in changing your title. <br />");
$stringData = $title."n";
fwrite($fh, $stringData);
fclose($fh);
}
$template = $_POST['temp'];
if (trim($template) == '') {
die("No template passed in!");
} else {
$structdir = $structure."/";
mkdir($structdir);
$fh = fopen($structdir."template.txt", 'w') or die("There was an error in changing your template. <br />");
$stringData = $template."n";
fwrite($fh, $stringData);
fclose($fh);
}
?>
希望这能有所帮助。
您是说这个/users/$username/title.txt
正好创建/users/$username/title.txt
所以你的问题是你需要先抓住$username,我不知道你的代码看起来怎么样,但也许是这个?
<?php $username=$_SESSION['username']; //retrieve the username
//rest of your code
$myFile = "/users/$username/title.txt";
$fh = fopen($myFile, 'w') or die("There was an error in changing your title. <br />");
$stringData = "$titlen";
fwrite($fh, $stringData);
fclose($fh);
$template = $_POST["temp"];
$myFile = "$structure/template.txt";
$fh = fopen($myFile, 'w') or die("There was an error in changing your template. <br />");
$stringData = "$templaten";
fwrite($fh, $stringData);
fclose($fh);
?>