PHP 用变量名创建路径和文件夹
在 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);
?>
In PHP I am trying to make a new database type folder for different people on sign up and add files. I could easily create files and write to them but for some reason every time i try to have PHP create folders using the persons username variable as the path, all it does is create a folder named $username.
Here is my code cut down to the basics of that part.
<?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);
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
试试这个
Try This
为了使其工作,您确实需要从字符串中分离出变量(如 Ben Griffiths 提到的)并检查它不为空。另外,请确保首先使用 mkdir() 创建目录(aschuler 也提到过这一点)。因此,代码可能看起来像这样,但如果不知道 $username、$struct、$title 和 $template 来自哪里,您可能需要对此进行一些更改:
希望这会有所帮助。
To make this work, you do need to break out the variable (as Ben Griffiths mentioned) from the string and check it isn't empty. Also, make sure you do make the directory first created using mkdir() (aschuler mentioned this as well). The code, therefore, may look something like this but without knowing where $username, $structure, $title and $template come from, you may need to alter this a little:
Hope this helps.
你是说这个
/users/$username/title.txt
创建了完全/users/$username/title.txt
所以你的问题是你需要捕获 $username首先,我不知道你的代码是什么样子,但也许是这样?
You're saying that this
/users/$username/title.txt
create exactly/users/$username/title.txt
so Your problem is you need to catch $username first, I don't know how your code look but maybe this?