dtxw20878
2017-09-25 09:01
浏览 82
已采纳

基于文本文件的顺序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?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试使用以下代码创建基于文本文件的顺序URL旋转器(原始来源):

 &lt;?php 
 $ linksfile =“urlrotator.txt”; 
 $ posfile =“pos.txt”; 
 
 $ links = file($ linksfile)  ; 
 $ numlinks = count($ linksfile); 
 
 $ fp = fopen($ posfile,'r +')或die(“无法打开posfile”); 
 
flock($ fp,LOCK_EX); 
  $ num = fread($ fp,1024); 
if($ num&lt; $ numlinks-1){
 fwrite($ fp,$ num + 1); 
} else {
 fwrite($ fp,0)  ; 
} 
 nflock($ fp,LOCK_UN); 
 nclclose($ fp); 
 
header(“Location:{$ links [$ num]}”); 
?&gt; 
    
 
 

在我测试之后,我发现它会在pos.txt的现有内容之后将新的位置编号作为字符串附加,因此脚本只能在第一时间工作。

我尝试在 if之前添加以下代码行 else 语句,以便在更新之前清除pos.txt的现有内容。

  file_put_contents($ posfile,“”); 
    
 
 

然后在重定向行发出错误,说明 Undefined index:......

可能会出错?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doubiankang2845 2017-09-25 09:36
    已采纳

    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);
    
    已采纳该答案
    打赏 评论

相关推荐 更多相似问题