帮助在PHP中同时写入两个文件?

时间:2011-04-17 01:11:49

标签: php

在下面的脚本中,我尝试在两个文件中同时编写,但不执行。我怎么能这样做?

$filename1 = "guestbook.doc" ;
$filename2 = "cour.doc" ;

$name = htmlspecialchars($_POST['name']);

$email = htmlspecialchars($_POST['email']);

$message = stripslashes(nl2br(htmlentities($_POST['message'])));

$d = date ( "d/m/Y H:i:s" )

$handle1 = fopen($filename1, "w+");
$handle2 = fopen($filename2, "a+");

if ($handle1 && $handle2) {
    fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
    fwrite($handle2, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
}
if ($handle1) {
    fclose($handle1);
}
if ($handle2) {
    fclose($handle2);
}

then
{
header('Location: contact.php?' . http_build_query($_POST));
}
?>

3 个答案:

答案 0 :(得分:2)

有一点我注意到有点奇怪的是:

then
{
header('Location: contact.php?' . http_build_query($_POST));
}

then不是有效的控制结构。它是if / elseif / else

答案 1 :(得分:0)

在PHP中写入文件是程序性的,它会在移到handle2之前等待handle1被写入。它不会同时写它们。必须发生错误或者没有进入if语句if($handle1 && $handle2)。由于权限问题,它可能无法打开这些文件进行写入?有任何错误吗?

尝试用这样的东西替换if语句并查看它是否中断?

if (is_writable($filename1) or die ("Can not write to ".$filename1)) {
  fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}
if (is_writable($filename2) or die ("Can not write to ".$filename2)) {
  fwrite($handle2, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}

答案 2 :(得分:0)

只要在另一个下面写一个就可以完美。

<?php

$filename = "guestbook.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle1 = fopen($filename, "w+");
$size = filesize($filename);
fwrite($handle, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
$text = fread($handle, $size);
fclose($handle);

$filename = "cour.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle = fopen($filename1, "w+");
$size = filesize($filename1);
fwrite($handle, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
$text = fread($handle, $size);
fclose($handle);

?>