using fseek to insert string before last line

2019-08-16 09:30发布

I am trying to write a very basic registration module for blueimp.net's AjaxChat. I have a script that writes to the user config file.

$userfile = "lib/data/users.php";
$fh = fopen($userfile, 'a');
$addUser = "string_for_new_user";
fwrite($fh, $addUser);
fclose($fh);

But I need it to insert $addUser before the very last line, which is ?>

How would I accomplish this using fseek?

标签: php fwrite fseek
2条回答
我欲成王,谁敢阻挡
2楼-- · 2019-08-16 09:32

Another way to accomplish this is using the SplFileObject class (available as of PHP 5.1).

$userfile = "lib/data/users.php";
$addUser = "\nstring_for_new_user\n";
$line_count = 0;

// Open the file for writing
$file = new SplFileObject($userfile, "w");

// Find out number of lines in file
while ($file->valid()) {
   $line_count++;
   $file->next();
}

// Jump to second to last line
$file->seek($line_count - 1);

// Write data
$file->fwrite($add_user);

I haven't tested this (I can't on the computer I'm using right now) so I'm not sure if that works exactly like that. The point here is really the cool seek() method of the SplFileObject which can seek by line rather than how fseek() seeks by bytes.

查看更多
爷、活的狠高调
3楼-- · 2019-08-16 09:40

If you always know that the file ends with ?> and nothing more, you can:

$userfile = "lib/data/users.php";
$fh = fopen($userfile, 'r+');
$addUser = "string_for_new_user\n?>";
fseek($fh, -2, SEEK_END);
fwrite($fh, $addUser);
fclose($fh);

To further enhance the answer: you're going to want to open your file in mode r+ because of the following note regarding fseek:

Note:

If you have opened the file in append (a or a+) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling fseek() will be undefined.

fseek($fh, -2, SEEK_END) will place the position at the end of the file, and then move it backwards by 2 bytes (the length of ?>)

查看更多
登录 后发表回答