基于文本文件的顺序URL旋转器无法正常工作

I'm trying to create a text file-based sequential url rotator by using the following code (original source):

<?php
$linksfile ="urlrotator.txt";
$posfile = "pos.txt";

$links = file($linksfile);
$numlinks = count($linksfile);

$fp = fopen($posfile, 'r+') or die("Failed to open posfile");
flock($fp, LOCK_EX);
$num = fread($fp, 1024);
if($num<$numlinks-1) {
  fwrite($fp, $num+1);
} else {
  fwrite($fp, 0);
}
flock($fp, LOCK_UN);
fclose($fp);

header("Location: {$links[$num]}");
?>

After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.

I tried adding the following line of code before the if else statement in order to clear the existing content of pos.txt before updating it.

file_put_contents($posfile, "");

But then error ocurred at the line of redirection saying Undefined index: ...... .

Where could possibly go wrong?

I believe your problem comes from the mode you are using. When you say

After my testing, I found that it keeps appending new position number as a string after the existing content of pos.txt and thus the script only works at the first time.

it points me to the mode usage of fopen.

The mode you should use is w, as it will "replace" the content of what is inside pos.txt.

$fp = fopen($posfile, 'w') or die("Failed to open posfile");

Doing so will prevent your from accessing what was in pos.txt. So you need to have something like this:

$num = file_get_contents($posfile);
$fp = fopen($posfile, 'w') or die("Failed to open posfile");
flock($fp, LOCK_EX);
if($num<$numlinks-1) {
  fwrite($fp, $num+1);
} else {
  fwrite($fp, 0);
}
flock($fp, LOCK_UN);
fclose($fp);