PHP-在文件夹中创建文件夹


PHP - Make folder in folder

我很确定我根本没有权限。无论如何,谢谢你的回答!我将切换到自我主持,所以我知道我有许可!

(我会删除这个,但它说我不能b/c有答案)

首先,$username的实际值是多少?你确认它不是空的了吗?

像这样处理文件系统可能会导致几个不同的问题。我喜欢多做一些额外的检查,这样如果有什么事情失败了,我就更容易知道原因了。我还喜欢尽可能使用绝对目录名,这样我就不会遇到相对路径的问题。

$filesDir = '/path/to/files';
if (!file_exists($filesDir) || !is_dir($filesDir)) {
    throw new Exception("Files directory $filesDir does not exist or is not a directory");
} else if (!is_writable($filesDir)) {
    throw new Exception("Files directory $filesDir is not writable");
}
if (empty($username)) {
    throw new Exception("Username is empty!");
}
$userDir = $filesDir . '/' . $username;
if (file_exists($userDir)) {
    // $userDir should be all ready to go; nothing to do.
    // You could put in checks here to make sure it's 
    // really a directory and it's writable, though.
} else if (!mkdir($userDir)) {
    throw new Exception("Creating user dir $userDir failed for unknown reasons.");
}

mkdir()有一些非常有用的选项,用于设置权限和使文件夹深入到多个级别。如果您还没有,请查看PHP的mkdir页面。

为了安全起见,请确保您的异常不会向最终用户显示系统路径。当代码进入公共服务器时,您可能希望从错误消息中删除文件夹路径。或者进行配置,使您的异常记录下来,但不会显示在网页上。

这是这种场景的算法。

  1. 检查文件夹是否存在
  2. 如果文件夹存在,请将文件夹命名为其他名称或添加一个随机数
  3. 创建新文件夹。

    http://pastebin.com/VefbrzRS

试试这个。

mkdir ("./files/$username");

这些不是同一个文件夹吗?files亚历克斯和files亚历克斯是相同的。你是指文件/$username和文件/$username/files吗?您对同一目录执行了两次操作,因此出现错误

如果您使用的是Linux或MacO,还有另一种情况是调用shell的mkdir函数。

它看起来像:

system('mkdir -p yourdir/files/$username')