开发者

Write one value to two text files simultaneously

开发者 https://www.devze.com 2022-12-15 12:06 出处:网络
Im using the following php to send the contents of an HTML <form> to a text file: $filename =\"polls\".\"/\".time() .\'.txt\';

Im using the following php to send the contents of an HTML <form> to a text file:

$filename =  "polls"."/".time() .'.txt';
    if (isset($_POST["submitwrite"])) {
        $handle = fopen($filename,"w+");
        if ($handle) {
            fwrite($handle, $_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."开发者_如何学Go¬".time());
            fclose($handle);
        }

At the same time as creating the text file, with the contents of the form, I also want to write the time() to a file which already exists, So will use 'a+'. They will need to be stored as comma seperated values.

Can anyone suggest how I can do this at the same time?


Just open two files:

$handle1 = fopen($filename1, "w+");
$handle2 = fopen($filename2, "a+");
if ($handle1 && $handle2) {
    fwrite($handle1, $_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
    fwrite($handle2, time() + "\n");
}
if ($handle1) {
    fclose($handle1);
}
if ($handle2) {
    fclose($handle2);
}


You could also write to (including appending) the files using file_put_contents().

if (isset($_POST["submitwrite"])) {
    // Could perhaps also use $_SERVER['REQUEST_TIME'] here
    $time = time();

    // Save data to new file
    $line = sprintf("%s¬%s¬%s¬%s¬%s¬%d", 
            $_POST["username"], $_POST["pollname"], $_POST["ans1"], 
            $_POST["ans2"], $_POST["ans3"], $time);
    file_put_contents("polls/$time.txt", $line);

    // Append time to log file
    file_put_contents("timelog.txt", "$time,", FILE_APPEND);
}
0

精彩评论

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