PHP fopen(“filename”,w)创建〜1的文件

时间:2013-03-19 15:15:19

标签: php fopen fwrite

我正在尝试用PHP编写一个文件。到目前为止它的工作“有点”。

我有{Rob,Kevin,Michael}格式的一系列名字。我使用代码行

foreach($Team as $user)
 {
print_r($user);
    //create a file for each user
    $file = fopen("./employee_lists/".$user, 'w');
    //I have also tried: fopen("employee_lists/$user", 'w');
    // ... ... ...
    //write some data to each file.
 }

这按预期工作:print_r显示“Rob Kevin Michael”,但文件名保存如下:ROB~1,KEVIN~1,MICHAE~1

当我稍后在我的代码中使用这些文件时,我想将“Rob”的用户名与ROB~1联系起来,我将不得不采取一些额外的步骤来完成这项工作。我觉得我正在使用fopen错误,但它完全符合我想要的减去这个小命名方案的问题。

2 个答案:

答案 0 :(得分:2)

您的$user变量似乎包含文件系统路径的无效字符(我最好的猜测是新行)。

尝试:

$file = fopen("./employee_lists/".trim($user), 'w');

答案 1 :(得分:1)

在将$ user用作文件名之前,您应该清理它。

$pattern = '/(;|\||`|>|<|&|^|"|'."\n|\r|'".'|{|}|[|]|\)|\()/i';
// no piping, passing possible environment variables ($),
// seperate commands, nested execution, file redirection,
// background processing, special commands (backspace, etc.), quotes
// newlines, or some other special characters
$user= preg_replace($pattern, '', $user);
$user= '"'.preg_replace('/\$/', '\\\$', $user).'"'; //make sure this is only interpreted as ONE argument

顺便说一下,使用用户名作为文件名是一个坏主意。最好使用数字ID。

相关问题