2017-09-25 45 views
0

我尝试使用下面的代码(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]}"); 
?> 

我的测试后,我发现它在pos.txt的现有内容之后不断追加新的位置编号,因此该脚本仅在第一次运行。

我试着在if else语句前添加下面一行代码,以便在更新之前清除pos.txt的现有内容。在重定向的行内容时发生

file_put_contents($posfile, ""); 

但随后错误说Undefined index: ......

哪里有可能出错?

+0

它是否设置在一个循环?或者你连续多次拨打它? –

+0

@JulienLachal对不起,但我不太明白。我第一次测试时,它工作并将我重定向到正确的位置,但随后的时间不起作用。 –

回答

1

我相信你的问题来自你正在使用的模式。当你说

经过我的测试后,我发现它在pos.txt的现有内容之后不断追加新的位置号码作为字符串,因此脚本只在第一次工作。

它指向我的模式使用fopen

您应该使用的模式是w,因为它将“替换”pos.txt内部的内容。

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

这样会阻止你访问什么在pos.txt。所以你需要这样的东西:

$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); 
+1

谢谢!这有帮助!我还发现原代码第四行中的count($ linksfile)应该是count($ links)'。 –