开发者

php fopen - name of file

开发者 https://www.devze.com 2022-12-15 10:19 出处:网络
I currently have: <?php if (isset($_POST[\"su开发者_StackOverflow社区bmitwrite\"])) { $handle = fopen(\"writetest.txt\",\"w+\");

I currently have:

<?php
    if (isset($_POST["su开发者_StackOverflow社区bmitwrite"])) {
        $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...


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


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+'

0

精彩评论

暂无评论...
验证码 换一张
取 消