2017-09-25 42 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)'。 –