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?

  • 写回答

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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料