在PHP中,我尝试在注册和添加文件时为不同的人创建一个新的数据库类型文件夹。我可以轻松地创建文件并写入它们但是由于某种原因,每当我尝试使用人员用户名变量作为路径创建PHP文件夹时,它所做的就是创建一个名为$ 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 = "$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);
?>
答案 0 :(得分:1)
试试这个
<?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);
?>
答案 1 :(得分:0)
为了使这项工作,您需要从字符串中分解变量(如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);
}
?>
希望这有帮助。
答案 2 :(得分:0)
您说这个/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 = "$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);
?>