2010-01-01 57 views
1

的名字我目前有:PHP的fopen - 文件

<?php 
    if (isset($_POST["submitwrite"])) { 
     $handle = fopen("writetest.txt","w+"); 
     if ($handle) { 
      fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time()); 
      fclose($handle); 
     } 
    } 
?> 

不过,我需要调整的文件名是动态的,而不是“writetest.txt”我想它是:用户名+ pollname +时间.txt取$ _post变量。

我也想改变这些文件存储到/结果的目录。

请帮助...

+1

那么问题是什么? – notnoop 2010-01-01 21:29:11

回答

1

你的意思是做这样的事情?

$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt'; 
if (isset($_POST["submitwrite"])) { 
    $handle = fopen($filename,"w+"); 
    // etc... 

还是我不理解你?

编辑
为了解决BalusC指出的问题,这是一个比较完整的解决方案。
它确保$_POST['username']$_POST['pollname']值有效,因此它们不会创建无效或可能有害的$filename

<?php 
$basedir = '/results'; 
$basename = 'time.txt'; 

// Get user and poll names 
$username = $_POST['username']; 
$pollname = $_POST['pollname']; 

// Counteract the old magic_qutoes feature, if needed. 
if(get_magic_quotes_gpc()) { 
    $username = stripslashes($username); 
    $pollname = stripslashes($pollname); 
} 

// Validate user and poll names. 
$regexp = '/^[\w\d\_\-\. \']+$/iu'; 
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) { 
    echo 'Username or pollname is invalid. Aborting!'; 
} 
else { 
    // Compile the complete file name 
    $filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename; 

    // Write to the file 
    if (isset($_POST["submitwrite"])) { 
     $handle = fopen($filename,"w+"); 
     if ($handle) { 
      fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time()); 
      fclose($handle); 
     } 
    } 
} 
?> 
+0

Perfecto!一些你如何理解我...... – CLiown 2010-01-01 21:46:19

+0

如果有一个用户名为“foo /../bar”的用户会怎么样? – BalusC 2010-01-01 21:48:21

+0

@BalusC:只允许a-z,0-9和_和 - 用户名? – Midas 2010-01-01 21:53:58

1

创建的fopen(至少尝试)的文件,如果它不存在,所以 $文件名= $的用户名。 $ pollname。 $时间。 '。文本'; $ handle = fopen($ filename,'w +');

会正常工作。 顺便说一下,w +将指针放在文件的开头。如果文件已经有一些数据,它会首先截断它。如果你想追加数据到文件,你可能想使用'a +'