1

我正在尝试用 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 不正确,但它正是我想要的,减去这个小命名方案问题。

4

2 回答 2

2

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

尝试:

$file = fopen("./employee_lists/".trim($user), 'w');
于 2013-03-19T15:23:18.910 回答
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

By the way, it's a bad idea using an user name for a file name. It's better to use a numeric id.

于 2013-03-19T15:25:13.943 回答