使用PHP写入TXT

时间:2013-12-12 19:44:41

标签: php html forms

我正在尝试解析在HTML文件中输入的文本。我的代码应该调用PHP脚本来输出输入到服务器上的.txt的字段。我已确保将777的CHMOD权限授予Web服务器上的.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"); }
?>

2 个答案:

答案 0 :(得分:0)

使用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);

答案 1 :(得分:-1)

在表单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"); }
?>