tags:

views:

56

answers:

2

I currently have:

<?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);
        }
    }
?>

However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.

I would also like to change the directory these files are stored in to /results.

Help please...

+1  A: 

You mean doing something like this?

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

Or am I not understanding you?

Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $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);
        }
    }
}
?>
Atli
Perfecto! Some how you managed to understand me...
danit
What would happen if there's an user with username `"foo/../bar"` ?
BalusC
@BalusC: Only allow a-z, 0-9 and _ and - in usernames?
Midas
Good point, BalusC. I'll post a more secure version.
Atli
A: 

fopen creates (at least tries) the file if it does not exist, so $filename = $username . $pollname . $time . '.txt'; $handle = fopen($filename, 'w+');

will work fine. By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'

marvin