我有一个存储用户信息的文件。文件名是 johndoe (无扩展名):
johndoe
John,Doe,JohnDoe,johndoe@gmail.com,abcd1234
我正在尝试以这种方式从文件中获取John
,Doe
和JohnDoe
:
index.php
$filename = explode("/", $_SERVER["PHP_SELF"])[2];
$userpath = "http://192.168.0.1/member/" . $filename;
$userfile = fopen($userpath,"r");
$username = explode(",",fgets($userfile))[2];
$firstname = explode(",",fgets($userfile))[0];
$lastname = explode(",",fgets($userfile))[1];
其中$_SERVER["PHP_SELF"]
当前返回/member/johndoe/index.php
。
当我使用explode(",",fgets($userfile))
打印数组print_r()
时,我得到:
Array ( [0] => John [1] => Doe [2] => JohnDoe [3] => johndoe@gmail.com [4] => abcd1234 )
但是,我无法访问任何数组元素。例如,回显explode(",",fgets($userfile))[2]
会引发错误:
注意::未定义的偏移量:第8行的192.168.0.1/member/johndoe/index.php中的2
答案 0 :(得分:2)
使用fgets
后,文件指针将移到刚读取的最后一个字节旁边的字节。
您不需要每次都调用它:
$filename = explode("/", $_SERVER["PHP_SELF"])[2];
$userpath = "http://192.168.0.1/member/" . $filename;
$userfile = fopen($userpath,"r");
// Split into parts and assign values to corresponding variables
list($firstname, $lastname, $username) = explode(',', fgets($userfile));
// Alternative syntax (PHP 7.1+)
// [$firstname, $lastname, $username] = explode(',', fgets($userfile));