PHP字符串比较导致未定义的偏移3错误

时间:2012-01-10 00:14:52

标签: php

我正在尝试比较存储在一个平面文件中的几个数组值(我知道,mysql要好得多,但它是一个分配,所以请使用过时的方法),一些表单从$ _POST变量发送用户凭据尽管文件中只有一行数据,但我仍然收到以下错误:

注意:未定义的偏移量:第70行的./login.php中的3

我在下面列出了一些令人讨厌的代码行以及浏览器的一些前导码和打印出的结果(在基本尝试解决问题时我运行了一个print_r命令并且显然已经返回2个数组但是可以'弄清楚为什么......?)。

如果我可以添加任何有助于解决此问题的其他信息,请告诉我们 - 我将非常愿意帮忙。

用户注册数据在register.php文件

的代码片段中捕获
<?php
$filename = '../../private_data/filewriting.php';

if (isset($_POST['register']) && count($errors)==0) {

    // Submission was OK, so display thank-you message
    $output .= '<p><strong>Thanks for registering with us! Please click <a href="index.php">here</a> to login to the site using your Username and Password</strong></p>';

    $handle = fopen($filename, 'a');

    fwrite($handle, "\n".$clean['fullname']."|".$clean['address']."|".$clean['postcode']."|".$clean['username']."|".$clean['password']);

    fclose($handle);
}
?>

然后在login.php文件

中的此片段中检查用户输入登录详细信息
<?php
$output = '';
$filename = '../../private_data/filewriting.php';

if (isset($_POST['submit']) && count($errors)==0) {

    $lines = file($filename);

    foreach ($lines as $line) {
        $arr = explode('|', $line);
        print_r($arr);
        echo '<br />';

        // The next line is the problematic line 70             
        if ($arr[3]==$clean['username'] && $arr[4]==$clean['password']) {
            $_SESSION['username'] = $clean['username'];
            $_SESSION['password'] = $clean['password'];
            $output .= '<p><strong>Password and Username match - Thank you for logging in. Please continue to browse the site using the links above.</strong></p>';
        }
    }
}
?>

提交登录详细信息后,此文件的输出如下:

数组([0] =&gt;)

注意:未定义的偏移量:第70行的./login.php中的3

数组([0] =&gt;测试用户[1] =&gt; 123 Shallot Street,The Big Onion [2] =&gt; BN21 0LK [3] =&gt; testuser [4] =&gt;密码)< / p>

密码和用户名匹配 - 感谢您登录。<​​/ p>

1 个答案:

答案 0 :(得分:1)

如果你参考这个php参考:

http://php.net/manual/en/function.file.php

您会看到该示例显示了一个键值引用,如下所示:

$lines = file($filename);

foreach ($lines as $line_num => $line) {
    $arr = explode('|', $line);
    print_r($arr);
    echo '<br />';

    if ($arr[3]==$clean['username'] && $arr[4]==$clean['password']) {
        $_SESSION['username'] = $clean['username'];
        $_SESSION['password'] = $clean['password'];
        $output .= '<p><strong>Password and Username match - Thank you for logging in. Please     continue to browse the site using the links above.</strong></p>';
    }
}

看看是否有帮助。

另外,我是否误读了这个?看起来你故意添加一个新行:

fwrite($handle, "\n".$clean['fullname']."|".$clean['address']."|".$clean['postcode']."|".$clean['username']."|".$clean['password']);

为什么不摆脱那个\ n