2013-03-19 37 views
1

我想在PHP中编写一个文件。到目前为止它工作“种”。PHP的fopen(“文件名”,W)创建〜1的文件

我有{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〜1,KEVIN〜1,MICHAE〜1

当我在我的代码中稍后使用这些文件时,我想将“Rob”的用户名与ROB〜1关联起来,我将不得不采取一些额外的步骤来执行此操作。我觉得我不正确地使用fopen,但它正是我想要的减去这个小命名方案问题。

+1

你在使用什么操作系统?视窗? – blamonet 2013-03-19 15:16:25

+3

'$ user'的确切值是什么?问题描述似乎表明主机系统不使用长文件名,这是荒谬的,我怀疑是不可能的 - 我怀疑PHP会在不仅仅因为年龄的系统上编译。也许这是因为'$ user'包含一个用于文件名的无效字符(我最好猜测是一个新行),这是一个副作用,尽管我确信'fopen()'应该在这种情况下完全失败。尝试'$ file = fopen(“./ employee_lists /”。trim($ user),'w');' – DaveRandom 2013-03-19 15:16:41

+0

您是否尝试过使用扩展名来存储文件名?像$ file = fopen(“./ employee_lists /".$ user。”。txt“,'w'); – mokk 2013-03-19 15:18:39

回答

2

它看起来像你的$user变量包含一个无效的字符文件系统路径(我最好的猜测会是一个新行)。

尝试:

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

你应该使用它作为一个文件名前消毒$用户。

$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。